gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:52:06 25 4
gpt4 key购买 nike

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

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

但是,管理员可能会在用户登录时更改声明的值(我们的 token 有效期为 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);

关于Asp.Net Identity - 登录后更新声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com