微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我使用asp.net身份(WebApi 2,MVC 5,而不是.net核心)在从我的单页应用程序登录时向我的用户身份添加声明.这看起来像这样(我已经删除了对无效名称,锁定帐户等的检查)
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,但身份验证将不会了解此信息.

我可以看到,在运行时我可以添加删除我的身份声明,但这些更改不会持续超过当前请求.有没有办法在运行中更新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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐