我正在使用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;
}
我们假设管理员撤销User A
对特定帐户的访问权限。如何强制User A
重新生成ClaimsIdentity
?请记住,它不在User A
的上下文中。而且我不想等到Cookie过期(并且会自动生成新的ClaimsIdentity
。
有可能吗?是不是有办法告诉服务器将User A
的cookie视为无效并强制它重新生成?
我想要这种行为的原因是创建一个自定义AuthorizeAttribute
我可以放在我的控制器上,检查Claims
以查看User
是否有权访问,以避免额外往返数据库。
答案 0 :(得分:5)
您无法将其声明存储在Cookie中,但会在管道早期的每个身份请求中应用它们。你必须破解Startup.Auth.cs
才能做到这一点。我正在做here。
以下是您可以使用的要点:
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;
}
}
您需要在每个请求上应用声明的缺点,这可能不是非常高效。但是在适当的地方适量的缓存会有所帮助。此外,这段代码并不是最容易上手的地方,因为它处于管道的早期阶段,您需要管理自己DbContext
和其他依赖项。
优点是声明会立即应用于每个用户的请求,您可以立即更改权限,而无需重新登录。