【问题标题】:Adding a claim to IdentityRole in IdentityServer 4在 IdentityServer 4 中添加对 IdentityRole 的声明
【发布时间】:2017-12-30 13:46:52
【问题描述】:

在将我的应用程序升级到 .NET Core 2.0 和 IdentityServer 4 之前,我曾经拥有此功能。

var role = new IdentityRole("Admin");
role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = "IsAdmin", ClaimValue = "True" });

这不再有效,我尝试了谷歌,但看不到任何清晰的东西。确切的错误是:

如何使用 IdentityServer 4 向 IdentityRole 添加声明?

【问题讨论】:

  • 你到底遇到了什么错误?
  • 添加了显示错误的屏幕截图。

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


【解决方案1】:

您可以通过 , 来解决此问题

NuGet 安装 Microsoft.AspNet.Identity.AspNetCoreCompat。然后添加 Microsoft.AspNet.Identity.AspNetCoreCompat.

的引用

之后,您将得到如下图所示的异常。

安装 Microsoft.AspNet.Identity.EntityFramework, 并修复所有编译器错误。

【讨论】:

    【解决方案2】:

    您需要先使用CreateAsync 创建role,然后再使用AddClaimAsync

      var role = new IdentityRole("Admin");
      await _roleManager.CreateAsync(role);
      await _roleManager.AddClaimAsync(role, new Claim(type: "IsAdmin", value: "True"));
    

    【讨论】:

      【解决方案3】:

      您现在无法直接访问 Claims 集合。 您必须改用 RoleManager 的相关功能。 注入您的 RoleManager,然后按如下方式使用它:

      var role = new IdentityRole("Admin");
      var claim = new Claim(type: "IsAdmin", value: "True");
      await roleManager.CreateAsync(role);
      await roleManager.AddClaimAsync(role, claim);
      

      根据@Joe 的输入更新

      【讨论】:

      • 您需要等待roleManager ... 并在添加声明之前创建角色。在两个语句之间添加await _roleMgr.CreateAsync(role);。更新你的答案,我会投票。
      • 这不是我说的,它不起作用。你在发帖前是否在 OP 设置中测试过它?
      • @Joe,再次更新,这可能是我的错,但我从未告诉过我要发布完整的解决方案,这是一个 sn-p。
      • @Joe,感谢您通过投票和复制答案的支持:)
      猜你喜欢
      • 2021-03-24
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      • 2015-06-20
      • 2023-03-22
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      相关资源
      最近更新 更多