如何在更改ASP.NET身份验证当前用户的用户名后更改身份验证Cookie。

18

使用带有 Entity Framework 6.0.0-rc1(这是 Visual Studio 2013 RC 的一部分)的 asp.net identity 版本 1.0.0-rc1。

尝试为用户提供更改他们的UserName的机会。在AuthenticationIdentityManager下似乎没有此功能,因此我使用 EF 更改了数据(获取当前用户的 User 对象,更改 UserName 并保存更改)。

问题在于身份验证 cookie 保持不变,因此下一次请求失败,因为没有这样的用户。

过去我使用以下代码解决了 Forms 身份验证的问题。

var formsAuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
var isPersistent = FormsAuthentication.Decrypt(formsAuthCookie.Value).IsPersistent;
FormsAuthentication.SetAuthCookie(newUserName, isPersistent);

我该如何处理asp.net身份验证以更新cookies?

更新

以下代码似乎可以更新身份验证cookie。

var identity = new ClaimsIdentity(User.Identity);
identity.RemoveClaim(identity.FindFirst(identity.NameClaimType));
identity.AddClaim(new Claim(identity.NameClaimType, newUserName));
AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant
    (new ClaimsPrincipal(identity), new AuthenticationProperties {IsPersistent = false});
剩下的问题是:如何从当前身份验证Cookie中提取IsPersistent的值?
1个回答

16

如何使用AspNet.Identity登录/验证用户以使用Asp.Net MVC5 RTM位?

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

对于RC1,您可以使用类似的代码。

AuthenticationManager.SignOut();
IdentityManager.Authentication.SignIn(AuthenticationManager, user.UserId, isPersistent:false);

要保持持久值,您需要访问身份验证 cookie 并检索状态。

更新:

请使用适当的 AuthenticationType 替换 "Bearer"。还要确保在发出签名票证时,设置了 AuthenticationProperties.IsPersistent。

bool isPersistent=false;
var authContext = await Authentication.AuthenticateAsync("Bearer");
if (authContext != null)
{
   var aProperties = authContext.Properties;
   isPersistent = aProperties.IsPersistent;
}

这段代码可能适用于RTM(目前尚未广泛使用)。在RC1中,没有DefaultAuthenticationTypes和UserManager.CreateIdentityAsync()。 - aleyush
第二个问题:我如何获取当前的IsPersistent值(我的目标只是更改UserName,而不是其他任何内容)? - aleyush
在发布VS2013之前,最好使用夜间构建进行试验。这里的一些开发人员评论指出,许多RC1类在即将于11月与VS2013一起发布的RTM中不可用。 - jd4u
1
我已经升级到夜间版本,但问题仍然存在:我如何获取当前的IsPersistent值? - aleyush
您的最新更新已经帮助解决了问题(将“Bearer”更改为DefaultAuthenticationTypes.ExternalCookie)。已标记为答案。 - aleyush
重要提示:在最近的OWIN项目中,默认模板代码使用DefaultAuthenticationTypes.ApplicationCookie而不是DefaultAuthenticationTypes.ExternalCookie。如果您在代码中未能更改这个小细节,那么上面的所有内容都将失效。 - Chris Moschini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接