asp.net-mvc – 更新用户声明不起作用.为什么?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 更新用户声明不起作用.为什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用ASP.NET MVC 5.1与Owin和声明身份验证.

用户更改电子邮件后,我需要更新用户声明,所以我在控制器中试过:

  1. ClaimsIdentity identity = (ClaimsIdentity)User.Identity;
  2. Claim claim = identity.FindFirst(ClaimTypes.Email);
  3. identity.RemoveClaim(claim);
  4. identity.AddClaim(new Claim(ClaimTypes.Email,newEmail));
  5.  
  6. IOwinContext context = new OwinContext();
  7.  
  8. context.Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  9. context.Authentication.SignIn(identity);

声明已更改,但是当我刷新页面时,电子邮件声明是原来的…

看来cookie没有被更新.任何想法我做错了什么?

并且可以从身份获取“IsPersistent”的值,所以当我再次签名时,我将具有相同的值?

谢谢,

米格尔

解决方法

我有同样的问题,所以只是想在这里总结我的发现.正如克里斯所说,答案的依据确实在这里: How to change authentication cookies after changing UserName of current user with asp.net identity,但是我发现线程有点难以跟踪,而且这个问题并不是一个直接的重复.

开始,从当前OWIN上下文获得AuthenticationManager.一旦你这样做,你可以通过调用AuthenticateAsync方法获取“isPersistent”(和原来的SignIn调用的其他属性)的值.然后更新当前用户身份的声明,您只需要替换AuthenticationResponseGrant属性的值,如下所示:

  1. var identity = (ClaimsIdentity)User.Identity;
  2.  
  3. // Call AddClaim,AddClaims or RemoveClaim on the user identity.
  4.  
  5. IOwinContext context = Request.GetOwinContext();
  6.  
  7. var authenticationContext =
  8. await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
  9.  
  10. if (authenticationContext != null)
  11. {
  12. authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(
  13. identity,authenticationContext.Properties);
  14. }

它是实际更新cookie的AuthenticationResponseGrant属性的最终设置.

希望这有助于其他读者.

猜你在找的asp.Net相关文章