1

我正在使用 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 时更新它的声明?

4

1 回答 1

1

由于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,因此下一个请求应正确获取您的更改。

于 2013-06-14T07:12:31.693 回答