Asp.net-Mvc

使用 IdentityServer 4 時如何在 Api 項目中添加附加聲明

  • October 15, 2018

對不起我的英語不好。

我有三個項目:IdentityServer、Ensino.Mvc、Ensino.Api。IdentityServer 項目從 IdentityServer4 庫中提供主要的身份資訊和聲明 - 聲明配置文件、聲明地址、聲明 Sid 等。Ensino.Mvc 項目在令牌中獲取此資訊並將其發送到 API,以便 MVC 被授予對資源的訪問權限。令牌包含 IdentityServer 提供的所有聲明。但是在 API 中,我需要生成其他特定於 API 的聲明,例如:與令牌中的聲明 Sid 對應的聲明 EnrollmentId。而且我想在 HttpContext 中添加這個聲明以供將來使用。有人可以告訴我如何實現這一目標嗎?

我在 Startup.ConfigureServices 中有這段程式碼:

// Add identity services
       services.AddAuthentication("Bearer")
           .AddIdentityServerAuthentication(options =>
           {
               options.Authority = "http://localhost:5100";
               options.RequireHttpsMetadata = false;
               options.ApiName = "beehouse.scope.ensino-api";
           });

       // Add mvc services
       services.AddMvc();

在其他項目中,沒有 API,只有 mvc,我繼承UserClaimsPrincipalFactory並覆蓋CreateAsync了添加額外的聲明。我喜歡在 API 項目中做這樣的事情。可能嗎?

最好的方法是什麼?

編輯:經過一番研究,我想做的是:通過 IdentityServer 進行身份驗證,並根據聲明和特定的 api 數據庫數據在 api 中設置授權。

在您的 API 項目中,您可以將自己的事件處理程序添加到options.JwtBearerEvents.OnTokenValidated. 這是ClaimsPrincipal已設置的點,您可以向身份添加聲明或向主體添加新身份。

services.AddAuthentication("Bearer")
  .AddIdentityServerAuthentication(options =>
  {
      options.Authority = "http://localhost:5100";
      options.RequireHttpsMetadata = false;
      options.ApiName = "beehouse.scope.ensino-api";

      options.JwtBearerEvents.OnTokenValidated = async (context) => 
      {
          var identity = context.Principal.Identity as ClaimsIdentity;

          // load user specific data from database
          ...

          // add claims to the identity
          identity.AddClaim(new Claim("Type", "Value"));
      };
  });

請注意,這將在對 API 的每個請求上執行,因此如果您從數據庫載入資訊,最好記憶體聲明。

此外,Identity Server 應該只負責辨識使用者,而不是他們做什麼。他們所做的是特定於應用程序的(角色、權限等),因此您在辨識這一點並避免與 Identity Server 的邏輯交叉方面是正確的。

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