Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-identity-2

How to add claims during user registration


I'm using ASP.NET MVC 5 project with identity 2.1.0 and VS2013 U4. I want to add claims to user during registration in order to be stored in db. These claims represent user custom properties.
As I created a web page for administrator to create/edit/delete users, I'm still using create method from AccountController to create a user, but I don't want to login that user. How can I add those claims to the user ?


Solution

  • You probably already have a UserManager class. You can use that one to create users and to add claims.

    As an example in a controller:

    // gather some context stuff
    var context = this.Request.GetContext();
    
    // gather the user manager
    var usermanager = context.Get<ApplicationUserManager>();
    
    // add a country claim (given you have the userId)
    usermanager.AddClaim("userid", new Claim(ClaimTypes.Country, "Germany"));
    

    In order for this to work you need to implement your own UserManager and link it with the OWIN context (in the example it's ApplicationUserManager which basically is class ApplicationUserManager : UserManager<ApplicationUser> { } with only a small amount of configuration added). A bit of reading is available here: https://msdn.microsoft.com/en-us/library/dn613290%28v=vs.108%29.aspx