Joe*_*Joe 8 asp.net owin 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);
}
Run Code Online (Sandbox Code Playgroud)
此时,一切都按预期工作.我可以通过AuthorizationFilterAttribute我的api 上的as方法来检查用户的声明.
但是,管理员可能会在用户登录时更改声明的值(我们的令牌有效期为14天).作为一个例子,我们有一个名为Locationsvalue的声明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))
}
});
Run Code Online (Sandbox Code Playgroud)
当用户的权限发生更改时,您可以更新他们的安全戳:
UserManager.UpdateSecurityStamp(userId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
976 次 |
| 最近记录: |