Joe*_*oel 5 asp.net asp.net-mvc-5 asp.net-identity asp.net-identity-2
我正在使用Asp.NET Identity 2.1.0,我存储了Accounts一个User可以访问的列表,作为声明.该ClaimsIdentity时生成User迹象:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add Claims concerning Account
userIdentity.AddClaim(new Claim("AccountList", SerializedListOfAccounts));
return userIdentity;
}
Run Code Online (Sandbox Code Playgroud)
假设管理员撤销User A对特定帐户的访问权限.我User A该如何强制再生ClaimsIdentity呢?请记住,它不是在上下文中User A.我不想等到cookie过期(并ClaimsIdentity自动生成一个新的.
可能吗?有没有办法告诉服务器将User Acookie视为无效并强制它重新生成?
我想要这种行为的原因是创建一个自定义AuthorizeAttribute,我可以放在我的控制器上,检查Claims是否User有访问权限,以避免额外的数据库往返.
您不能将他们的声明存储在cookie上,而是在管道早期的每个请求中应用它们.你必须破解Startup.Auth.cs这样做.我做的只是在这里.
以下是您可以使用的要点:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
Provider = GetMyCookieAuthenticationProvider(),
// other configurations
});
// other usual code
}
private static CookieAuthenticationProvider GetMyCookieAuthenticationProvider()
{
var cookieAuthenticationProvider = new CookieAuthenticationProvider();
cookieAuthenticationProvider.OnValidateIdentity = async context =>
{
// execute default cookie validation function
var cookieValidatorFunc = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
TimeSpan.FromMinutes(10),
(manager, user) =>
{
var identity = manager.GenerateUserIdentityAsync(user);
return identity;
});
await cookieValidatorFunc.Invoke(context);
// sanity checks
if (context.Identity == null || !context.Identity.IsAuthenticated)
{
return;
}
// get your claim from your DB or other source
context.Identity.AddClaims(newClaim);
};
return cookieAuthenticationProvider;
}
}
Run Code Online (Sandbox Code Playgroud)
您需要在每个请求上应用声明的缺点,这可能不是非常高效.但在适当的地方适量的缓存将有所帮助.此外,这段代码并不是最容易上手的地方,因为它很早就在管道中,您需要管理自己DbContext和其他依赖项.
好处是声明会立即应用于每个用户的请求,您可以立即更改权限,而无需重新登录.
| 归档时间: |
|
| 查看次数: |
1045 次 |
| 最近记录: |