Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity 2.0 Claims not being added to the database

I'm using MVC5 with the latest version of Identity (2.1) I'm trying to create a user claim for the facebook access_token. I've never created a claim before, but my other Identity functionality works fine as far as I can tell.

I have this line of code in my Startup.Auth.cs:

    context.Identity.AddClaim(new Claim("urn:facebook:access_token",
 context.AccessToken, xmlSchemaString, "Facebook"));

The full piece of code is here if you need more reference: Integrate facebooksdk with Identity 2.0

If I put a break in the code on the line immediately after that line, I can see that everything is being retrieved properly, most importantly the content.AccessToken (which is a huge string). However, it never makes it to the database after completing a successful login.

As a test, I tried simplifying it, by changing the line to this:

context.Identity.AddClaim(new System.Security.Claims.Claim(ClaimTypes.Email, "[email protected]"));

Same outcome, no errors, but nothing is added to the database. I then tried adding this line of code in my IdentityModels.cs right where it tells you to put custom claims:

// Add custom user claims here
        userIdentity.AddClaim(new Claim(ClaimTypes.DateOfBirth, "01/01/1972"));

Same outcome...no errors and never makes it to the database. Can anyone think of any reason what my issue might be?

The only thing custom in my Identity setup is that I followed an article on how to use username instead of email (as the username). Also, I changed the Identity table names (e.g. UserClaims) in the OnModelCreating block which seems to be a fairly standard procedure.

I have a feeling it's going to be some rookie move, but at the moment, I'm stumped. Any help is much appreciated.

like image 829
Sum None Avatar asked Jul 09 '15 17:07

Sum None


People also ask

What is claims identity C#?

ClaimsIdentity(IIdentity) Initializes a new instance of the ClaimsIdentity class using the name and authentication type from the specified IIdentity. ClaimsIdentity(IIdentity, IEnumerable<Claim>) Initializes a new instance of the ClaimsIdentity class using the specified claims and the specified IIdentity.


1 Answers

Database persists your custom claims for the users. If user has any claims in the DB, they will be applied to the auth cookie with they login.

To add claims into the database you need to use UserManager:

await userManager.AddClaimAsync(userId, new Claim("MyClaimType", "MyClaimValue"));

If you are adding claims to ClaimsIdentity, then claims are not persisted in the database, but added to a cookie directly and will not be automatically re-added next time the user is logged-in.

like image 173
trailmax Avatar answered Oct 04 '22 04:10

trailmax