【问题标题】:How to change authentication cookies after changing UserName of current user with asp.net identity使用asp.net身份更改当前用户的用户名后如何更改身份验证cookie
【发布时间】:2013-10-13 18:57:27
【问题描述】:

将 asp.net 身份版本 1.0.0-rc1 与 Entity Framework 6.0.0-rc1(随 Visual Studio 2013 RC 一起提供)一起使用。

试图让用户有机会更改他们的UserNameAuthenticationIdentityManager 下似乎没有这个功能,所以我使用 EF 更改数据(获取当前用户的用户对象,更改用户名并保存更改)。

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

过去通过表单身份验证,我使用以下代码来解决这个问题。

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

我应该如何使用 asp.net 身份来更新 cookie?

更新

以下代码似乎更新了身份验证 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值?

【问题讨论】:

    标签: asp.net-mvc-5 owin asp.net-identity


    【解决方案1】:

    How do you login/authenticate a user with Asp.Net MVC5 RTM bits using AspNet.Identity?

    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()。
    • 第二个问题:如何获取当前的 IsPersistent 值(我的目标只是更改 UserName,而不是其他)?
    • 在 VS2013 发布之前,最好继续试用 nightly build。很少有来自开发人员的 cmets 表示许多 RC1 类在 RTM 中不可用,RTM 将于 11 月与 VS2013 一起发布。
    • 我已经升级到夜间构建,但问题仍然存在:如何获取当前的 IsPersistent 值?
    • 您的上次更新有所帮助(将“Bearer”更改为 DefaultAuthenticationTypes.ExternalCookie)。标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多