67

I am trying to find a document or example of how you would add custom claims to the user identity in MVC 5 using ASP.NET Identity. The example should show where to insert the claims in the OWIN security pipeline and how to persist them in a cookie using forms authentication.

Askolein
  • 3,250
  • 3
  • 28
  • 40
Kevin Junghans
  • 17,475
  • 4
  • 45
  • 62

4 Answers4

66

The correct place to add claims, assuming you are using the ASP.NET MVC 5 project template is in ApplicationUser.cs. Just search for Add custom user claims here. This will lead you to the GenerateUserIdentityAsync method. This is the method that is called when the ASP.NET Identity system has retrieved an ApplicationUser object and needs to turn that into a ClaimsIdentity. You will see this line of code:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

After that is the comment:

// Add custom user claims here

And finally, it returns the identity:

return userIdentity;

So if you wanted to add a custom claim, your GenerateUserIdentityAsync might look something like:

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

// Add custom user claims here
userIdentity.AddClaim(new Claim("myCustomClaim", "value of claim"));

return userIdentity;
dprothero
  • 2,683
  • 2
  • 21
  • 28
  • 3
    Say I added a claim like so `new Claim("FName", "John")` how would I then access that property in my Razor view? – J86 Apr 04 '15 at 20:54
  • 3
    `var userWithClaims = (ClaimsPrincipal) User;` `var fname = userWithClaims.Claims.First(c => c.Type == "FName");` – dprothero Apr 05 '15 at 03:51
  • 3
    Probably would want to put that kind of code into your Controller (or perhaps a base class for all your Controllers) and then put the value(s) into your Model or the ViewBag. But technically, it will work directly in the Razor view as I've written it here. – dprothero Apr 05 '15 at 03:53
  • 6
    In VS2015 you will find the `GenerateUserIdentityAsync()` method in the `IdentityModels.cs` file within the `App_Start` directory. – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Jul 22 '15 at 14:52
  • 4
    @MatthewT.Baker: I think you mean that IdentityModels.cs is in the Models directory, not App_Start? Also, I think this solution is incomplete. The documentation from Microsoft on adding custom claims (and I think the comments so far) do not explain the different effects of using userIdentity.AddClaim (which adds the claim to the cookies, but doesn't seem to change the AspNetUserClaims table), and manager.AddClaim(userId, claim), which adds the claim to the AspNetUserClaims table (NB it adds a new record even if an existing record with the same values exists), but not the cookies. – patrickjlee May 21 '16 at 22:39
  • @patrickL I agree that the above code only adds the claim to the cookie, but I found that if you add the claim to the AspNetUserClaims table like this: `ApplicationUserManager.AddClaimAsync(user.Id, new Claim("myCustomClaim", "value of claim"));` (for example at registration) then the call to manager.CreateIdentityAsync will "automatically" pull in the claims from the database table and add them to the cookie – PBMe_HikeIt Jul 01 '16 at 20:30
  • @dprothero any chance you could update `myCustomClaim` to be a real world example (or more) of what a claim might represent? – Simon_Weaver Dec 05 '17 at 02:29
  • 1
    @Simon_Weaver a claim can be literally anything... some piece of meta data about the user. In this case, the custom claim is some data you want to add to the identity that isn't already part of the ApplicationUser model stored in your database. Perhaps you need to consult an external system to learn more about the user. This would be the place to do this (which is why this method is Async, you could make other async calls to web services here). For more about claims, I suggest reading https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims – dprothero Dec 05 '17 at 15:16
48

Perhaps the following article can help:

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Brock"));
claims.Add(new Claim(ClaimTypes.Email, "brockallen@gmail.com"));
var id = new ClaimsIdentity(claims,DefaultAuthenticationTypes.ApplicationCookie);

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);
Vlince
  • 5,885
  • 7
  • 45
  • 62
9

If you want to add custom claims at the time of registration then this code will work:

            var user = new ApplicationUser
            {
                UserName = model.UserName,
                Email = model.Email
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            // Associate the role with the new user 
            await UserManager.AddToRoleAsync(user.Id, model.UserRole);
            // Create customized claim 
            await UserManager.AddClaimAsync(user.Id, new Claim("newCustomClaim", "claimValue"));
            if (result.Succeeded)
            {...etc
Uwe Köhler
  • 123
  • 1
  • 7
  • i understand this but its confusing as to what it does by default and what you need to setup. Email.... i do not have as a Claim on ClaimsPrincipal (User) i get that the above will probably add it... but what are the other on about, as they don't give content as to where they are calling the code,.if you know could you assist me. – Seabizkit Feb 29 '20 at 15:14
  • for example what happened to _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false); – Seabizkit Feb 29 '20 at 15:22
3

you can do the following in WEB API C #

var identity = new ClaimsIdentity(context.Options.AuthenticationType);          
        foreach(var Rol in roles)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, Rol));
        }
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Email, user.Correo));
        identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.Celular));
        identity.AddClaim(new Claim("FullName", user.FullName));
        identity.AddClaim(new Claim("Empresa", user.Empresa));
        identity.AddClaim(new Claim("ConnectionStringsName", user.ConnectionStringsName));

....