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

Ton*_*ist 9 c# asp.net authentication authorization asp.net-identity

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

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

2).AspNet.ApplicationCookie验证如何工作以及如何访问它?

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

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

更新:这是我的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);
                    }
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

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

Ton*_*ist 8

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

app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
Run Code Online (Sandbox Code Playgroud)

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

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

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

app.CreatePerOwinContext(() => IoCContainerManager.Container.Resolve<ApplicationDBContext>());
app.CreatePerOwinContext(() => IoCContainerManager.Container.Resolve<ApplicationUserManager>());
Run Code Online (Sandbox Code Playgroud)

并以这种方式注册类型:

container.Register(Component.For<ApplicationDBContext>().LifestylePerWebRequest());
container.Register(Component.For<ApplicationUserManager>().LifestylePerWebRequest());
Run Code Online (Sandbox Code Playgroud)


tra*_*max 5

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

UserManager.UpdateSecurityStampAsync(User.Id)
Run Code Online (Sandbox Code Playgroud)

并且不要设置validateIntervalTimeSpan.FromSeconds(0)- 这基本上意味着数据库将在每次请求时被点击.设置为10分钟.

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