微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在使用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属性的最终设置.

希望这有助于其他读者.

原文地址:https://www.jb51.cc/aspnet/250675.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐