我正在使用ASP.NET MVC 5.1与Owin和声明身份验证.
用户更改电子邮件后,我需要更新用户声明,所以我在控制器中试过:
- ClaimsIdentity identity = (ClaimsIdentity)User.Identity;
- Claim claim = identity.FindFirst(ClaimTypes.Email);
- identity.RemoveClaim(claim);
- identity.AddClaim(new Claim(ClaimTypes.Email,newEmail));
- IOwinContext context = new OwinContext();
- context.Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
- 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属性的值,如下所示:
- var identity = (ClaimsIdentity)User.Identity;
- // Call AddClaim,AddClaims or RemoveClaim on the user identity.
- IOwinContext context = Request.GetOwinContext();
- var authenticationContext =
- await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
- if (authenticationContext != null)
- {
- authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(
- identity,authenticationContext.Properties);
- }
它是实际更新cookie的AuthenticationResponseGrant属性的最终设置.
希望这有助于其他读者.