Asp.Net身份-登录后更新声明

时间:2018-07-31 16:06:26

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

当我从我们的单页应用程序登录时,我正在使用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);
}

在这一点上,一切都按预期进行。当我的api上的方法被调用时,我可以通过AuthorizationFilterAttribute来检查用户的声明。

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

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

1 个答案:

答案 0 :(得分:2)

如果要使用身份验证方式,则需要在每次登录时都进入数据库。您将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);