c# - ASP.net Identity SecurityStampValidator OnValidateIdentity regenerateIdentity 参数

标签 c# asp.net asp.net-mvc asp.net-identity owin

谁能解释为什么 ApplicationUser 类会创建以下辅助函数?

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, int> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    // Add custom user claims here
    return userIdentity;
}

我唯一能找到它被使用的地方是在 Startup.Auth.cs 文件中,作为 SecurityStampValidator.OnValidateEntity< 的 regenerateIdentity 回调参数 功能:

OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User, int>(
     validateInterval: TimeSpan.FromSeconds(15),
     regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
     getUserIdCallback: (id) => id.GetUserId<int>())

正如您从帮助器中看到的那样,它只是转身并调用 manager.CreatedIdentityAsync。他们使用辅助方法“污染”ApplicationUser 类而不是按如下方式设置 OnValidateEntity 是否有原因?

OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User, int>(
     validateInterval: TimeSpan.FromSeconds(15),
     regenerateIdentityCallback: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie),
     getUserIdCallback: (id) => id.GetUserId<int>())

最佳答案

*为清晰和简单而编辑

通过将身份生成方法抽象到用户类中,我们获得了可扩展性。

想象这样一种场景,您的应用程序有几种不同的用户类型,每种类型都可以实现自己的重新生成逻辑,而无需单独的身份验证类型。采用 IdentityUser 基类的 ApplicationUser 子类中的辅助方法。

public class ApplicationUser : IdentityUser
{      
    public string NickName {get; set; }
    public DateTime BirthDay {get; set;}


    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

我们现在可以将我们的声明分成不同的用户类,而无需修改 OWIN 身份验证管道,或者只需将基本 IdentityUser 子类化即可为每种类型创建一个新的 CookieAuthenticationProvider。

tldr;

它将身份重新生成的责任推给正在重新生成的用户类。类似于工厂方法模式。

关于c# - ASP.net Identity SecurityStampValidator OnValidateIdentity regenerateIdentity 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28947342/

相关文章:

c# - 统一来自相机的光线转换

c# - 将 Byte[] 转换为 Double

c# - Azure WCF 服务在 blob 存储文件上出现错误

asp.net - Razor 对通用扩展方法的支持

ASP.NET - 从客户端访问网页两次

c# - 如何使用带有 Serilog 的 postsharp 来分离日志记录方面?

c# - 为什么我的异步方法在执行调用方方法的下一行之前完成?

asp.net - 设计会在浏览器中受到影响吗?

c# - Razor 页面中 VB.NET 的 @@<text> 标签问题

c# - 服务器发送的事件或 SignalR 的性能会更好吗?