How to set a custom ClaimsPrincipal in MVC 5?

18,501

Solution 1

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.

Solution 2

•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.

Share:
18,501
BrunoLM
Author by

BrunoLM

I'm a Developer for Fun! Things I like Code Play games Anime / Manga Contact information [email protected] LinkedIn Facebook Site - https://brunolm.github.io/ Blog - http://blog.codingwise.com/

Updated on June 04, 2022

Comments

  • BrunoLM
    BrunoLM almost 2 years

    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?