Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 with ASP.NET Identity - Get Claims when user logs in

I am using OWIN 2.0, and after I log in a user, I want to retrieve an existing claim from the database but if I try to get the user's claims they are empty. If I put the same code in any of the subsequent controllers that gets called then the claims are there. It seems that the claims are not available until the next request after the initial login. Why is this?

var claimsIdentity = User.Identity as ClaimsIdentity;
var testClaim = claimsIdentity.Claims.Where(r => r.Type == "TestClaim").FirstOrDefault();
like image 226
Shiloh Avatar asked Oct 01 '22 16:10

Shiloh


1 Answers

Possibly because you haven't passed the claims into the initial login (or have missed calling CreateIdentityAsync)?

With an out-of-the-box MVC5 application, I do this in the SignInAsync method:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

    //Get the given name from somewhere
    var givenName = GetGivenName();

    identity.AddClaim(new Claim(ClaimTypes.GivenName, givenName));

    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

And this is called from the Login action.

like image 59
Brendan Green Avatar answered Oct 12 '22 13:10

Brendan Green