I created a custom principal class
public class FacebookPrincipal : ClaimsPrincipal
{
public JObject Data { get; set; }
}
And I want to use it. When the user logs in, I tried to set
var fbP = new FacebookPrincipal { Data = user.Data };
Thread.CurrentPrincipal = fbP;
AuthenticationManager.User = fbP;
HttpContext.User = fbP;
It works right after I set it, but when I go ho home/index
the value is lost
var user = HttpContext.GetOwinContext().Authentication.User;
var bbbb = this.User;
var cccc = ClaimsPrincipal.Current;
All the above methods return a Principal of type ClaimsPrincipal
and casting to FacebookPrincipal
returns null.
How do I set a custom principal?
ASP.NET Identity uses default ClaimsIdentityFactory to create before assigning ClaimsIdentity to User and Thread. You should create your own ClaimsIdentityFactory where you can add or manage additional information.
UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
userManager.ClaimsIdentityFactory = new MyClaimsIdentityFactory<IdentityUser>();
And the following code to create your implementation for ClaimsIdentity or its subclass.
public class MyClaimsIdentityFactory<IUser> : ClaimsIdentityFactory<IUser> where IUser : IdentityUser
{
public MyClaimsIdentityFactory(): base()
{
}
public override System.Threading.Tasks.Task<System.Security.Claims.ClaimsIdentity> CreateAsync(UserManager<IUser> manager, IUser user, string authenticationType)
{
// Override Creation of ClaimsIdentity and return it.
}
}
- Make sure you absolutely need to subclass ClaimsIdentity. You can add additional info as Claims.
- You shall use
base.CreateAsync
and merge theClaims
to your createdClaimsIdentity
.
•Make sure you absolutely need to subclass ClaimsIdentity. You can add additional info as Claims.
You should be careful about adding additional claims for supplementary information as a side effect can be a change to how the authorization policy will make decisions.
Today reading the question again I realise the issue is of the identity persistence and not how to create custom ClaimsIdentity!!!
- Instead of ClaimsPrincipal, working with ClaimsIdentity subclass may help in most cases of customizing.
- Second, as suggested by @marisks, you can use IUserClaimsStore to store claims issued from third-party for your user. only if the custom claims access is the problem.
Moreover, to persist the identity between two requests, use following code.
//you can create your own Identity here.
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//Or add custom claims. Claims Stored in IUserClaimStore are already populated by above creation.
identity.AddClaim(new Claim("ProfileDATA", "VALUE"));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
来源:https://stackoverflow.com/questions/19763807/how-to-set-a-custom-claimsprincipal-in-mvc-5