Get current principal as user of custom app in ASP.NET Core Identity
In previous versions of ASP.NET, if I wanted the custom class to be my current logged in user, then I did this: I let the FormsAuthentication module do its job, and then in the PostAuthenticateRequest event, I replaced (HttpContext.Current.User) with mine the usual main object that I retrieved from the database (with some caching for performance).
How can I achieve the same in ASP.NET Identity? I have my own ApplicationUser (not the default that comes with the ASP.NET Identity Identity EntityFramework) and my own UserStore.
In every authenticated request, I have HttpContext.User as a ClaimsPrincipal object. Is there a way to replace this with CustomClaimsPrincipal?
Is there any other better way to get the current ApplicationUser instance based on the current ClaimsPrincipal?
source to share
If you have your own IUserStore
, you can implement IUserClaimStore
to customize the claims ID that is passed to the main claim person.
If you need to replace the default claims principal, you must implement IUserClaimsPrincipalFactory
and pass your implementation in SignInManager
and register a configured manager in your owin context.
It should look like the picture shown. (Assuming you are using a basic ASP.NET identity, the interfaces and constructors for Identity v2 may differ!)
class CustomClaimsFactory<TUser> : Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<TUser>
where TUser : class
{
public Task<ClaimsPrincipal> CreateAsync(TUser user)
{
// create and return your custom principal
}
}
class OwinStartup
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(CreateSignInManager);
}
Microsoft.AspNetCore.Identity.SignInManager CreateSignInManager()
{
UserManager manager; // the manager that uses your custom IUserStore
IHttpContextAccessor accessor; // I don't know where to get it from...
var factory = new CustomClaimsFactory();
return new SignInManager(manager, accessor, factory, null, null, null);
}
}
For ASP.Net Core , an OWIN-like launch configuration is done using dependent injection .
source to share