在MVC5中的Owin Identity中重新生成reinrateIdentityCallback中的Claim

Luk*_*s K 11 asp.net-mvc claims owin asp.net-identity

我正在使用带有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()))
            }
        });
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)

问题是,我无法重复索赔,而且我总是必须为它获得新的价值.在我看到Identity dll的调查之后this,该用户的实例没有声明,因为它是来自数据库的新用户,并且userIdentity只有标准声明为Id和UserName,它们是由CreateIdentityAsync方法创建的.从HttpContext.Current获取用户是不可能的,在这个地方它是null.

重用Claim以保留Cookie中的某些值的最佳方法是什么?我可能误解了索赔的目的.请事先提供帮助

小智 13

您可以通过执行此操作获得相同的结果(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)
Run Code Online (Sandbox Code Playgroud)