2

在 MVC5 Web 应用程序上,我使用的是 Asp.net Identity。当用户注册时,我添加了一些声明,它们保存在数据库中,并在用户登录时恢复。这非常有效。现在,基于一个参数(登录页面上的复选框),我想在用户登录时向用户添加特定的声明。但是有一个问题:此声明将仅存在于该用户特定的会话中(如果同一用户登录另一个浏览器实例或设备并且不选中该复选框,他将不会拥有该声明)。我没有使用并且不希望依赖 asp.net 会话。

我很容易实现这一点,只需在调用时添加声明AuthenticationManager.SignIn

private async Task SignInAsync(CustomUser user, bool isPersistent, bool myCustomTemporaryClaim)
{
    var identities = await user.GenerateUserIdentityAsync(UserManager);

    if (myCustomTemporaryClaim)
    {
        identities.AddClaim(new Claim(CustomClaimTypes.MyCustomTemporaryClaim, "true"));
    }

    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identities);
}

这工作正常。但是 VS 模板上的默认 asp.net 身份实现被配置为每 30 分钟“刷新”一次身份。发生这种情况时,我放弃了我的自定义声明。所以,我想知道的是,在 asp.net 身份重新生成 cookie 之前,是否可以“拦截”并获取我的自定义声明值?

我可以删除,regenerateIdentityCallback但我不知道这可能是什么结果。

4

1 回答 1

2

我确定您现在已经知道该怎么做,但以防万一其他人偶然发现此线程,我认为您只需将 AddClaim 移动到 GenerateUserIdentityAsync 方法中。然后,当刷新发生并调用 regenerateIdentityCallback 时,您的声明将被重新添加。

对于您的条件 myCustomTemporaryClaim,您可以在 GenerateUserIdentityAsync 中包含一个参数。有关如何执行此操作以及如何更改回调的更多详细信息,请参阅此帖子: ExpireTimeSpan 在 MVC Identity (2.0.1) 中 regenerateIdentity / validateInterval 持续时间后被忽略

即(注意我使用 int 作为我的 UserId)

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

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager, bool myCustomTemporaryClaim)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        if (myCustomTemporaryClaim)
        {
            userIdentity.AddClaim(new Claim(CustomClaimTypes.MyCustomTemporaryClaim, Convert.ToString(true)));
        }

        return userIdentity;
    }
}

顺便说一句,我最终阅读您的帖子的原因是因为我在调用 SignInAsync 时一直丢失我的自定义声明,所以我只是替换了这个

var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

有了这个

var identity = await user.GenerateUserIdentityAsync(UserManager);
于 2015-03-13T13:28:05.663 回答