在 MVC5 中的 Owin Identity 中重用 regenerateIdentityCallback 中的声明
-
21-12-2019 - |
题
我正在使用具有 Owin 身份的 MVC5。
我正在努力重用 regenerateIdentityCallback 中的任何自定义声明。
我在 Startup 中有此配置(如新 MVC 项目的标准模板中提供的)
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, Guid>(
validateInterval: TimeSpan.FromSeconds(10),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (user) => Guid.Parse(user.GetUserId()))
}
});
GenerateUserIdentityAsync 看起来像这样:(以及模板中的几乎标准)
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, Guid> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// I want here instead of generating new one, just reuse the previous one
userIdentity.AddClaim(new Claim(ClaimTypes.Sid, Guid.NewGuid().ToString()));
return userIdentity;
}
问题是,我无法重用该声明,并且我总是必须为其获取新的价值。经过对 Identity dll 的调查后我发现, this
用户的实例没有声明,因为它是数据库中的新用户并且 userIdentity
仅具有标准声明作为 Id 和 UserName,它们是通过 CreateIdentityAsync 方法创建的。从 HttpContext.Current 获取用户是不可能的,在这个地方它是空的。
重用声明以保留 Cookie 中的某些值的最佳方法是什么?我可能误解了索赔的目的。提前感谢您的帮助
解决方案
您可以通过这样做获得相同的结果(context.Identity 是以前的身份):
OnValidateIdentity = context => SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, DtbsUser, Guid>(
validateInterval: TimeSpan.FromSeconds(30),
regenerateIdentityCallback:
(manager, user) =>
user.GenerateUserIdentityAsync(manager, context.Identity),
getUserIdCallback: (ci) => Guid.Parse(ci.GetUserId())).Invoke(context)
其他提示
我放弃并创造了自己的 SecurityStampValidator
其功能与原始版本完全相同,但将当前的 ClaimsIdentity 作为参数传递给 regenerateIdentityCallback。对这个解决方案一点也不满意,但它确实有效。
OnValidateIdentity = MySecurityStampValidator.OnValidateIdentity<ApplicationUserManager, DtbsUser, Guid>(
validateInterval: TimeSpan.FromSeconds(10),
regenerateIdentityCallback: (manager, user, previousIdentity) => user.GenerateUserIdentityAsync(manager, previousIdentity),
getUserIdCallback: user => Guid.Parse(user.GetUserId()))
不隶属于 StackOverflow