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属性的最终设置.

希望这有助于其他读者.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....