Asp.Net Identity - 登录后更新声明

2024-04-25

当我的用户从我们的单页应用程序登录时,我使用 asp.net 身份(WebApi 2、MVC 5,而不是 .net core)添加对用户身份的声明。看起来像这样(我已经取消了对无效名称、锁定帐户等的检查)

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var userManager = context.OwinContext.GetUserManager<CompWalkUserManager>();
    var user = await userManager.FindByNameAsync(context.UserName);
    var check = await userManager.CheckPasswordAsync(user, context.Password);
    if (!check)
    {
        await userManager.AccessFailedAsync(user.Id);
        context.SetError("invalid_grant", invalidUser);
        return;
    }

    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
        OAuthDefaults.AuthenticationType);
    ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
        CookieAuthenticationDefaults.AuthenticationType);

    //These claims are key/value pairs stored in the local database
    var claims = GetClaimsForUser(user);
    cookiesIdentity.AddClaims(claims);
    oAuthIdentity.AddClaims(claims);


    AuthenticationProperties properties = CreateProperties(user.UserName);
    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
    context.Validated(ticket);
    context.Request.Context.Authentication.SignIn(cookiesIdentity);
}

至此,一切都按预期进行。我可以通过以下方式检查用户的声明AuthorizationFilterAttribute当我的 api 上的方法被调用时。

但是,管理员可能会在用户登录时更改声明的值(我们的令牌有效期为 14 天)。作为示例,我们有一个名为Locations值为EditAndDelete。管理员可能会将此值更改为NoAccess在数据库中,但身份验证不会知道这一点。

我可以看到在运行时我可以添加或删除我的声明identity,但这些更改在当前请求之后不会持续存在。有没有办法动态更新 cookie 中的身份验证票?我希望能够更新我的Identity使用新值,而无需用户注销。


如果您想采用身份方式来执行此操作,则需要在每次登录时访问数据库。您设置了SecurityStamp验证间隔为 0:

app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        { 
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromSeconds(0),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    });

当用户的权限发生更改时,您可以更新他们的安全戳:

UserManager.UpdateSecurityStamp(userId);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Asp.Net Identity - 登录后更新声明 的相关文章

随机推荐