2017-10-06 81 views
1

我的問題: [授權(角色=「L1」)和User.IsInRole(「L1」)正在尋求索賠名「http://schemas.microsoft.com/ws/2008/06/identity/claims/role」,而不是「角色」如何IdentityServer4 /身份配置作用的聲明名稱

在具體的: 我已經通過以下步驟創建IdentityServer4與標準的身份數據庫(http://docs.identityserver.io/en/release/quickstarts/6_aspnet_identity.html):

  • 新建項目
    • ASP.NET核心的Web應用程序(.NET核心)
    • ASP.NET 1.1的核心
    • Web應用程序
    • 更改身份驗證
      • 個人用戶帳戶
  • 添加IdentityServer4.AspNetIdentity + Config.cs + ...

然後我創建了一個MVC客戶端。驗證工作正常。我還得到一份索賠清單。

我使用表AspNetUsers,AspNetUserRoles和AspNetRoles爲IdentityServer4配置角色。角色被添加到索賠名稱爲「角色」的索賠中。

如果我嘗試在MVC-Client中授權我的控制器操作,似乎我的角色的聲明名稱是錯誤的。

我該如何解決衝突?我必須將「角色」映射到「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。

+1

找到的答案不適用於asp.net-core,因爲具有通用ClaimsPrinciple-Parameter的UserManager不存在於Microsoft.AspNetCore.Identity中。 – Nikolaus

回答

2

我找到了自己的答案。 我必須指出,我正在使用 JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); 以避免重新命名聲明名稱(請參閱代碼)。

由此產生的問題是ClaimsPrinciple仍在查找以「http://schemas.microsoft.com/ws/2008/06/identity/claims/role」命名的角色。

這可以用OpenIdConnectOptions.TokenValidationParameters間接修正。

public class Startup 
{ 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
    // ... 

    // Avoid claim mapping to old ms soap namespaces. Avoid replace "role" by "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" 
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); 

    app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions 
    { 
     // ... 

     // https://leastprivilege.com/2016/08/21/why-does-my-authorize-attribute-not-work/ 
     TokenValidationParameters = new TokenValidationParameters 
     { 
     NameClaimType = "name", 
     RoleClaimType = "role", // The role claim type is named "role" instead of "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" 
     } 

    }); 
    } 
} 
相關問題