Reputation: 1985
I am using BrockAllen.MembershipReboot
Having an issue with the claims handling in relation to when exactly the claims get updated. The code below should demonstrate my problem...
private function UpdateGender(string newGender)
{
account.RemoveClaim(ClaimTypes.Gender);
account.AddClaim(ClaimTypes.Gender, newGender);
userAccountService.Update(account);
// since we've changed the claims, we need to re-issue the cookie that
// contains the claims.
authSvc.SignIn(User.Identity.Name);
}
[HttpPost]
public JsonResult function myAjaxMethod(){
UpdateGender("male");
string gender = System.Security.Claims.ClaimsPrincipal.Current.Claims.GetValue(ClaimTypes.Gender);
// the "gender" variable will never be "male" in this request (unless it was already male)
// because although we've set the cookie it hasn't updated the claim until the next request
// when it reads the cookie again.
return Json(gender);
}
My question is this:
Is there a way to force the System.Security.Claims.ClaimsPrincipal.Current.Claims.GetValue()
method to update it's claims at the point where the cookie is issued?
Upvotes: 1
Views: 9599
Reputation: 48279
Since the ClaimsPrincipal.Current
accesses the Thread.CurrentPrincipal
locally, I guess you could just update the current thread principal for the lifetime of the current request.
// your existing code
account.RemoveClaim(ClaimTypes.Gender);
account.AddClaim(ClaimTypes.Gender, newGender);
// additional code that updates current thread principal
ClaimsPrincipal principal = Thread.CurrentPrincipal as ClaimsPrincipal;
if ( principal != null ) {
ClaimsIdentity identity = principal.Identities.ElementAt(0);
identity.AddClaim( new Claim( ClaimTypes.Gender, "asdf" ) );
}
// this works now
string gender = ClaimsPrincipal.Current.Claims.GetValue( ClaimTypes.Gender );
Note that since you are reissuing the cookie, the next request should correctly pick up your changes.
Upvotes: 1