asp.net-mvc - 在 MVC5 中的 Owin Identity 中重用 regenerateIdentityCallback 中的声明

标签 asp.net-mvc asp.net-identity owin claims

我正在使用具有 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 中的某些值的最佳方法是什么?我可能误解了 claim 的目的。提前感谢您的帮助

最佳答案

这样做可以获得相同的结果(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)

关于asp.net-mvc - 在 MVC5 中的 Owin Identity 中重用 regenerateIdentityCallback 中的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25042822/

相关文章:

javascript - 避免 AngularJS 部分 View 在 IE 中缓存

javascript - 使用内置功能在 MVC6 中使用 JQuery AJAX 提交 Razor 表单

c# - 将参数传递给 OWIN 主机

javascript - MVC Razor 中的级联下拉验证失败

asp.net-mvc - ASP.NET MVC 模型/ View 模型验证

asp.net-mvc - 在使用 ASP.Net Identity 的 ASP.Net MVC 注册代码上运行单元测试时出错

c# - AspNetUsers 的主键不一致 "Object reference not set to an instance of an object"

c# - 拦截/停止经过身份验证的用户的 ASP.NET Identity 未经授权的重定向

c# - OWIN Cookie 与 FormsAuthentication