我有两个与此相关的问题:
1)我需要使用Asp.Net Identity 2添加/删除一些远程用户到Role后使用无效.AspNet.ApplicationCookie我尝试使用UpdateSecurityStamp,但由于没有更改密码或用户名,因此SecurityStamp保持不变 . 当我使用ApplicationRoleManger时,我可以看到用户角色已更新,但在User.Identity声明中,它们保持不变 . 2).AspNet.ApplicationCookie验证如何工作以及如何访问它?
我试图使用这段代码,但没有效果
What is ASP.NET Identity's IUserSecurityStampStore<TUser> interface?
更新:这是我的Cookie验证设置:
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)),
OnApplyRedirect = ctx =>
{
if (!IsApiRequest(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
});
我可以看到user.GenerateUserIdentityAsync(manager)仅在登录时被命中 .
2 回答
设置CookieAuthenticationOptions是不够的 . 当我在VS中创建新的ASP.NET MVC项目时,一切正常,并且每个请求都会触发GenerateUserIdentityAsync()(如果validateInterval为0) . 唯一的问题是你必须为每个请求注册上下文:
当我使用Winsdor Castle为每个请求创建上下文时,我从模板中删除了这些行 . 在ApplicationUserManager.Create中的注入方法中设置UserTokenProvider,它执行魔法perharps .
文档中没有任何关于此的内容,但最终它解决了问题 .
如果您使用自己的IoC,则可以通过这种方式解决依赖关系(例如,使用Castle Winsdor)
并以这种方式注册类型:
如果要在添加到角色后更改安全标记,请使用以下命令:
并且不要将
validateInterval
设置为TimeSpan.FromSeconds(0)
- 这基本上意味着数据库将在每次请求时被点击 . 设置为10分钟 .就在昨晚I've blogged about CookieAuthenticationProvider以及它如何使cookie无效 . 基本上,cookie包含有关创建时间的信息 . 如果它早于
validateInterval
,则访问数据库,获取用户记录并比较cookie和DB中的安全标记 . 如果邮票未更改,请发布包含新发布日期的新Cookie . 如果标记不匹配,则使cookie和注销用户无效 .