我正在使用BrockAllen.MembershipReboot
与索赔更新时间相关的索赔处理存在问题。下面的代码应该证明我的问题...
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);
}
我的问题是:
有没有办法强制System.Security.Claims.ClaimsPrincipal.Current.Claims.GetValue()
方法在发布cookie时更新它的声明?
答案 0 :(得分:3)
由于ClaimsPrincipal.Current
在本地访问Thread.CurrentPrincipal
,我猜你可以在当前请求的生命周期内更新当前线程主体。
// 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 );
请注意,由于您要重新发布Cookie,因此下一个请求应该正确地接收您的更改。