如何使用Asp.Net Identity 2将用户添加到角色后使.AspNet.ApplicationCookie失效?

我有两个与此相关的问题:

1)我需要使用Asp.Net Identity 2添加/删除一些远程用户到Role后无效.AspNet.ApplicationCookie我尝试使用UpdateSecurityStamp,但由于没有更改密码或用户名,因此SecurityStamp保持不变。 当我使用ApplicationRoleManger时,我可以看到用户角色已更新,但在User.Identity声明中,它们保持不变。

2).AspNet.ApplicationCookievalidation如何工作以及如何访问它?

我试图使用此代码,但没有任何效果

什么是ASP.NET Identity的IUserSecurityStampStore 接口?

更新:这是我的Cookievalidation设置:

app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity( validateInterval: TimeSpan.FromSeconds(0), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)), OnApplyRedirect = ctx => { if (!IsApiRequest(ctx.Request)) { ctx.Response.Redirect(ctx.RedirectUri); } } } }); 

我可以看到user.GenerateUserIdentityAsync(manager)仅在登录时被命中。

设置CookieAuthenticationOptions是不够的。 当我在VS中创建新的ASP.NET MVC项目时,一切正常,GenerateUserIdentityAsync()被每个请求命中(如果validateInterval为0)。 唯一的问题是你必须为每个请求注册上下文:

 app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext(ApplicationUserManager.Create); 

当我使用Winsdor Castle为每个请求创建上下文时,我从模板中删除了这些行。 在ApplicationUserManager.Create中的注入方法中设置UserTokenProvider,它执行魔法perharps。

文档中没有任何关于此的内容,但最终它解决了问题。

如果您使用自己的IoC,则可以通过这种方式解决依赖关系(例如,使用Castle Winsdor)

 app.CreatePerOwinContext(() => IoCContainerManager.Container.Resolve()); app.CreatePerOwinContext(() => IoCContainerManager.Container.Resolve()); 

并以这种方式注册类型:

 container.Register(Component.For().LifestylePerWebRequest()); container.Register(Component.For().LifestylePerWebRequest()); 

如果要在添加到角色后更改安全标记,请使用以下命令:

 UserManager.UpdateSecurityStampAsync(User.Id) 

并且不要将validateInterval设置为TimeSpan.FromSeconds(0) – 这基本上意味着每次请求都会TimeSpan.FromSeconds(0)数据库。 设置为10分钟。

就在昨晚, 我发表了关于CookieAuthenticationProvider以及它如何使cookie无效的博文 。 基本上,cookie包含有关创建时间的信息。 如果它早于validateInterval ,则访问数据库,获取用户记录并比较cookie和DB中的安全标记。 如果邮票未更改,请发布具有新发布日期的新cookie。 如果邮票不匹配,则使cookie和注销用户无效。