How to set a custom ClaimsPrincipal in MVC 5?

ε祈祈猫儿з 提交于 2019-12-04 12:52:28
jd4u

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 the Claims to your created ClaimsIdentity.

•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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!