【问题标题】:How can I use role GUIDs instead of names in ASP.NET Core Identity?如何在 ASP.NET Core Identity 中使用角色 GUID 而不是名称?
【发布时间】:2018-11-15 08:44:51
【问题描述】:

我一直在使用一些示例在 ASP.NET Core 中使用 Identity,但有些事情让我感到沮丧。尽管角色模型有一个主键 Id 和一个字符串 Name,但它是由各种内置服务传递的名称。

例如,当我调用_userManager.GetRolesAsync(user) 时,我会返回一个字符串名称列表。如果我想要身份证怎么办?没有用于此的 API,因此我必须使用角色管理器来获取所有角色并映射它们。默认情况下,角色名称不受唯一键的约束,因此这是不可靠的。

我一定错过了什么,但是什么?我现在的用例是我想用用户的角色填充 JWT 声明。就我而言,角色名称是我的应用程序内部的,我不想将这些暴露给客户。

【问题讨论】:

  • What if I want the IDs? 这是什么意思?您想获取用户角色ID吗?就像_dbContext.Roles.Single(x => x.Name == "Administrator")?
  • 我以为我的问题很清楚,抱歉。我想通过他们的Id 属性(在我的例子中是一个字符串化的 GUID)来引用角色,而不是他们的Name 属性。

标签: c# asp.net-core asp.net-identity


【解决方案1】:

对于_userManager.GetRolesAsync(user),它调用userRoleStore.GetRolesAsync

        public virtual async Task<IList<string>> GetRolesAsync(TUser user)
    {
        ThrowIfDisposed();
        var userRoleStore = GetUserRoleStore();
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }
        return await userRoleStore.GetRolesAsync(user, CancellationToken);
    }

要返回角色 ID 而不是角色名称,您可以通过实现自己的 UserStore 来自定义 userRoleStore.GetRolesAsync。

  • UserStore.cs

               public class CustomUserStore : UserStore<IdentityUser>
    {
        public CustomUserStore(DbContext context, IdentityErrorDescriber describer = null) : base(context, describer)
        {
        }
    
        public override async Task<IList<string>> GetRolesAsync(IdentityUser user, CancellationToken cancellationToken = default(CancellationToken))
        {
            var roleNames = await base.GetRolesAsync(user, cancellationToken);
            var roleIds = await Context.Set<IdentityRole>()
                                 .Where(r => roleNames.Contains(r.Name))
                                 .Select(r => r.Id)
                                 .ToListAsync();
    
            return roleIds;
        }
    }
    
  • 注册用户存储

        services.AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddUserStore<CustomUserStore>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            ;
        services.AddScoped<DbContext, ApplicationDbContext>();
    
  • 然后你会得到角色id集合

        var user = await _userManager.FindByNameAsync(User.Identity.Name);
        var roles = await _userManager.GetRolesAsync(user);
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2021-11-02
    • 2018-08-03
    • 2016-08-16
    相关资源
    最近更新 更多