【问题标题】:ASP.NET Identity properties extensionASP.NET 标识属性扩展
【发布时间】:2020-04-26 10:54:16
【问题描述】:

我正在使用 Asp.Net Identity 进行身份验证,我的要求是登录后目前我只能访问 User.Identity.Name,这只是用户名。

有什么方法可以在登录后添加更多属性

User.Identity.UserType
User.Identity.DepartmentId

为什么我想使用它来避免 Session 来识别 Views 上的用户。

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-identity


    【解决方案1】:

    首先,您需要向用户添加自定义声明。以创建用户后为例:

    await _userManager.Value.AddClaimAsync(user, new Claim("UserType", "SomeType"));
    

    然后创建一个扩展方法来读取声明值:

    public static string GetUserType(this IIdentity identity)
    {
        if (identity == null)
            throw new ArgumentNullException(nameof(identity));
    
        var claim = ((ClaimsIdentity)identity).FindFirst("UserType")?.Value;
    
        return claim ?? string.Empty;
    }
    

    登录后你可以访问用户类型:

    var userType = User.Identity.GetUserType();
    

    这是一个获得自定义声明的通用扩展:

    public static T Get<T>(this IIdentity identity, string propertyName)
    {
        if (identity == null)
            throw new ArgumentNullException(nameof(identity));
    
        var value = ((ClaimsIdentity)identity).FindFirst(propertyName)?.Value;
        if (value == null)
            return default(T);
    
        var type = typeof(T);
        if (type.IsEnum)
            return (T)Enum.Parse(typeof(T), value);
    
        return (T)Convert.ChangeType(value, typeof(T));
    }
    

    例如,您有一个UserType 的枚举:

    public enum UserType 
    {
        Admin,
        Editor,
        User,
    }
    
    var userType = User.Identity.Get<UserType>("UserType");
    var representativeId = User.Identity.Get<int>("DepartmentId");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多