1. 程式人生 > 程式設計 >IdentityServer4 QuckStart 授權與自定義Claims的問題

IdentityServer4 QuckStart 授權與自定義Claims的問題

最近在折騰IdentityServer4,為了簡單,直接使用了官方給的QuickStart示例專案作為基礎進行搭建。有一說一,為了保護一個API,感覺花費的時間比寫一個API還要多。

本文基於ASP.NET CORE 3.1,IdentityServer4 3.1.3。程式碼皆為關鍵程式碼,貼全了太多了。

好不容易跑起來了,最終的任務要落實到授權的工作上來。在API中使用Authorize用來限制使用者的訪問。

[Route("api/[controller]")]
[Authorize(Roles = "Administrator")]
[ApiController]
public class UserInfoController : ControllerBase
{
 /// <summary>
 /// 無參GET請求
 /// </summary>
 /// <returns></returns>
 [HttpGet()]
 [ProducesResponseType(typeof(ReturnData<IEnumerable<UserInfo>>),Status200OK)]
 public async Task<ActionResult> Get()
 {
 var info = new Info<UserInfo>();
 return Ok(new ReturnData<IEnumerable<UserInfo>>(await info.Get()));
 }

然而在使用的時候,雖然正確取得授權,但是卻無法正常訪問API,一直提示401沒有授權錯誤。仔細檢查,發現IdentityServer4返回的內容並沒有返回role的JwtClaimTypes,沒有它,Authorize無法正常工作。

{
 "nbf": 1587301921,"exp": 1587305521,"iss": "http://localhost:5000","aud": "MonitoringSystemApi","client_id": "webClient","sub": "c6c18d4d-c28e-4de5-86dd-779121216204","auth_time": 1587301921,"idp": "local","scope": [
 "roles","MonitoringSystemApi","offline_access"
 ],"amr": [
 "pwd"
 ]
}

實現

檢視Config.cs,IdentityServer4預設只返回兩種IdentityResource:openid和profile。按照官方的說法,這個東西定義的內容會返回到使用者的token。參考。那麼就果斷給它安排。

public static IEnumerable<IdentityResource> Ids =>
new List<IdentityResource>
{
 new IdentityResources.OpenId(),new IdentityResources.Profile(),new IdentityResource ("roles",new List<string> { JwtClaimTypes.Role }){ Required = true}
};

public static IEnumerable<Client> Clients =>
 new List<Client>
 {
 new Client
 {
  ClientId = "webClient",ClientSecrets = { new Secret("secret".Sha256()) },AllowOfflineAccess = true,AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,// scopes that client has access to
  AllowedScopes = {
  "roles","MonitoringSystemApi" }
 },

執行之前,需要確保資料庫中的使用者資料,已經包含role的Claim。

//新增使用者程式碼
bob = new ApplicationUser
{
 UserName = "bob"
};
var result = userMgr.CreateAsync(bob,"Pass123$").Result;
if (!result.Succeeded)
{
 throw new Exception(result.Errors.First().Description);
}
result = userMgr.AddClaimsAsync(bob,new Claim[]{
new Claim(JwtClaimTypes.Role,"Administrator"),new Claim(JwtClaimTypes.Name,"Bob Smith"),

執行程式,返回值依舊沒有任何變化,很挫敗,只能繼續折騰。
有研究通過實現IProfileService達到自定義Cliams。文章寫的很詳細,我這就不重複了,我實際試驗過,可以成功。

但是文章末尾的注意,很重要。

“那麼,通過profileservice頒發的claims,任意clients都能拿到”

說明這個優先順序是非常高的,可以覆蓋所有的行為,當然我們可以在IProfileService的實現上對許可權進行進一步的設定,不過還是挺麻煩的。參考實現,參考官方

作為懶人,必然不想再費勁去折騰許可權的問題,那麼是否有簡單點的辦法呢?

網上有一些問答說到了可以通過設定Scopes來達到目的。不過過於久遠,IdentityServer4已經沒有這個獨立的類了,說是已經被ApiResource取代了。

直覺上這個東西應該是指示要保護的API的相關內容的,好像和這個沒啥關係,不過也只能死馬當活馬醫了。修改config.cs,最終如下內容:

public static IEnumerable<ApiResource> Apis =>
new List<ApiResource>
{
 new ApiResource("pls",new[]{ "role"}),};

public static IEnumerable<Client> Clients =>
new List<Client>
{
new Client
{
 ClientId = "webClient",// scopes that client has access to
 AllowedScopes = {
 "pls"
 }
},

返回結果如下:

{
 "nbf": 1587301799,"exp": 1587305399,"aud": "pls","auth_time": 1587301799,"role": "Administrator","scope": [
 "pls","amr": [
 "pwd"
 ]
}

終於看見心心念唸的自定義Claim(role),可以去訪問API了。

注意,在Client中也有個Claims,添加了role並且設定AlwaysSendClientClaimsAlwaysIncludeUserClaimsInIdToken之後,會在token中新增client_roie欄位,這個是沒辦法用與授權的,可以理解為IdentityServer4直接指定了Client角色,並不是Identity中的角色概念。

後記

回過頭來仔細看官方的文件,ApiResource中的UserClaims就是用來幹這個的,折騰了半天,不如當時仔細看看文件了。

到此這篇關於IdentityServer4 QuckStart 授權與自定義Claims的文章就介紹到這了,更多相關IdentityServer4 QuckStart Claims內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!