【发布时间】:2017-10-06 21:19:04
【问题描述】:
我的问题: [Authorize(Roles = "L1")] 和 User.IsInRole("L1") 正在寻找声明名称“http://schemas.microsoft.com/ws/2008/06/identity/claims/role”而不是“角色”
具体来说: 我通过以下步骤 (http://docs.identityserver.io/en/release/quickstarts/6_aspnet_identity.html) 使用标准身份数据库创建了 IdentityServer4:
- 创建新项目
- ASP.NET Core Web 应用程序(.NET Core)
- ASP.NET Core 1.1
- Web 应用程序
- 更改身份验证
- 个人用户帐户
- 添加 IdentityServer4.AspNetIdentity + Config.cs + ...
然后我创建了一个 MVC 客户端。身份验证工作正常。我还得到一份索赔清单。
我在 IdentityServer4 中使用表 AspNetUsers、AspNetUserRoles 和 AspNetRoles 来配置角色。角色被添加到声明名称为“role”的声明中。
如果我尝试在 MVC 客户端中授权我的控制器操作,我的角色的声明名称似乎是错误的。
如何解决冲突?我必须将“角色”映射到“http://schemas.microsoft.com/ws/2008/06/identity/claims/role”吗?
这是我在 MVC 客户端中的控制器:
[Route("api/[controller]")]
public class CompaniesController : Controller
{
[HttpGet]
//[Authorize(Roles = "L1")] // This looks for the claim http://schemas.microsoft.com/ws/2008/06/identity/claims/role instead of role
public async Task<IEnumerable<Company>> GetCompaniesAsync()
{
var c = User.Identities.Count(); // 1
var nameOfExptectedRoleClaimType = User.Identities.First().RoleClaimType; // http://schemas.microsoft.com/ws/2008/06/identity/claims/role
var b0 = User.HasClaim(nameOfExptectedRoleClaimType, "L1"); // false
var b1 = User.HasClaim("role", "L1"); // true
var b2 = User.IsInRole("L1"); // false; looks for claim http://schemas.microsoft.com/ws/2008/06/identity/claims/role; used by [Authorize(Roles = "L1")]
var companies = await _crmApi.GetCompaniesAsync();
return companies;
}
}
我找到了这个答案 (https://stackoverflow.com/a/34226538/272357),但我不知道如何“注册”CustomPrinciple。
【问题讨论】:
-
找到的答案不适用于 asp.net-core,因为 Microsoft.AspNetCore.Identity 中不存在具有通用 ClaimsPrinciple-Parameter 的 UserManager。
标签: c# asp.net asp.net-core identity identityserver4