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, "test@example.com"));
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.
So your problem is that the DB is not hit to save the claims ? Claims are stored in a secured cookie with ASP.NET Identity ; ) The ASP.NET Identity Framework will read the cookie at the beginning of every request and populate the claims collection for you in my understanding. Just check that you can see the facebook claim from your MVC controller after login. I think there's actually no issue.
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
: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.