Asp.net-Core

IdentityServer4:為 Client_Credential Granttype 向客戶端主體添加自定義預設聲明

  • April 12, 2019

我正在使用 IdentityServer4,並嘗試在CLIENT創建令牌時向我添加自定義預設聲明。如果我使用隱式流程,這是可能的,IProfileService如下所示。

public class MyProfileService : IProfileService
{
   public MyProfileService()
   {

   }
   public Task GetProfileDataAsync(ProfileDataRequestContext context)
   {
       var claims = new List<Claim>
       {
           new Claim("DemoClaimType", "DemoClaimValue")
       };
       context.IssuedClaims = claims;
       return Task.FromResult(0);
   }
   public Task IsActiveAsync(IsActiveContext context)
   {
       context.IsActive = true;
       return Task.FromResult(0);
   }
}

在我的創業中

services.AddIdentityServer()
           .AddProfileService<MyProfileService>()

但是,這不適用於具有 client_credential 授權類型的客戶,因為它似乎cannot request OpenID scopes in client credentials flow。事實證明,Iprofileservice 顧名思義適用於Identity像配置文件這樣的 OpenId 範圍有效的資源。因為我無法請求具有 client_credential 授權類型的配置文件範圍,所以GetProfileDataAsync永遠不會被呼叫。

由於只與客戶合作,沒有使用者,我需要一種將聲明注入令牌的方法,而無需將它們添加到客戶端對象,如下所示

   new Client
{
   ClientId = "myclient",
   ClientName = "My Client",
   AllowedGrantTypes = GrantTypes.ClientCredentials,
   ClientSecrets = {new Secret("secret".Sha256())},
   AllowedScopes = new List<string> {"api"},                    
   AllowOfflineAccess = true,

   //I Don't want to do this
   Claims = new List<Claim>
   {   
       new Claim("type","value")
   }
}

我不希望上述情況,因為我不希望聲明成為數據庫中 client_claims 的一部分。我需要根據令牌請求即時創建它。我希望我的問題現在更清楚了。

經過一些詢問,我終於找到瞭如何做到這一點。我需要一種在請求令牌時向客戶端動態添加聲明的方法。

為了做到這一點,我必須擴展ICustomTokenRequestValidator然後將我的類包含在 Startup.cs 徹底依賴注入

public class DefaultClientClaimsAdder : ICustomTokenRequestValidator
{
   public Task ValidateAsync(CustomTokenRequestValidationContext context)
   {
       context.Result.ValidatedRequest.Client.AlwaysSendClientClaims = true;
       context.Result.ValidatedRequest.ClientClaims.Add(new Claim("testtoken","testbody"))

       return Task.FromResult(0);
   }
}

在 Startup.cs 中配置服務

services.AddTransient<ICustomTokenRequestValidator, DefaultClientClaimsAdder>();

引用自:https://stackoverflow.com/questions/43894146