Skip to content

Instantly share code, notes, and snippets.

@Eonasdan
Last active December 14, 2021 15:28
Show Gist options
  • Select an option

  • Save Eonasdan/0f99c74445e3afa6c827cab7de6faed7 to your computer and use it in GitHub Desktop.

Select an option

Save Eonasdan/0f99c74445e3afa6c827cab7de6faed7 to your computer and use it in GitHub Desktop.
PrincipalProvider is a way to pass information about a user to various layers of a project

PrincipalProvider is a way to pass information about a user to various layers of a project. In this example, the web project registers a concrete WebPrincipalProvider and provides the user from the http context.

You could create a concrete for use in a job/service to provide a system user for example.

You can inject IPrincipalProvider in a service and then call _principalProvider.ClaimsUser.Claims... or get the UserId.

using System.Security.Claims;
namespace YourProject.Interfaces
{
/// <summary>
/// This interface provides a way to inject the user into the services without
/// crossing responsibilities.
/// </summary>
/// <example>
/// var userId = _principalProvider.ClaimsUser.GetUserId();
/// </example>
public interface IPrincipalProvider
{
ClaimsPrincipal User { get; }
}
}
namespace YourProject.Web
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IPrincipalProvider, WebPrincipalProvider>();
}
}
}
using System.Security.Claims;
using Akron.Business.Interfaces;
using Microsoft.AspNetCore.Http;
namespace YourProject.Web
{
public class WebPrincipalProvider : IPrincipalProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
public WebPrincipalProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public ClaimsPrincipal User => _httpContextAccessor.HttpContext.User;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment