我使用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
,但身份验证将不会知道此信息 .
我可以看到,在运行时我可以添加或删除我的 identity
中的声明,但这些更改不会持续超过当前请求 . 有没有办法在运行中更新cookie中的身份验证票?我希望能够使用新值更新我的 Identity
,而无需用户注销 .
1 回答
如果你想采用Identity方式,你需要在每次登录时点击数据库 . 您将
SecurityStamp
验证间隔设置为0:为用户更改权限后,您将更新其安全性戳: