0

我已將身份服務器3與成員身份重新啓動數據庫一起設置爲我的授權服務器,並且還開發了一個Web Api項目,該項目將由JavaScript Web應用程序訪問。身份服務器3隱式授予,基於角色的授權

使用隱式流程,客戶端可以登錄並獲取id_token和access_token。現在我有幾個問題,我將很感激一些詳細的答案:

  1. id_token有什麼功能?獲得後,我可以用它做什麼?

  2. 用戶的角色作爲聲明(例如,「角色」,「管理員」的關鍵值)存儲在數據庫中。我現在如何執行基於角色的授權?這似乎是id_token包含這些聲明,但access_token沒有。當我沿着Api請求發送我的access_token作爲承載時,api如何知道發送用戶具有哪些角色?

  3. 在web API控制器,我想用於訪問用戶的信息:

    變種用戶=用戶作爲ClaimsPrincipal;

使用此代碼,我無法獲得有關用戶的任何內容;用戶名,ID等。另外,當我在控制器中使用user.Claims時,我無法訪問存儲在數據庫中的聲明。如何有兩組索賠,一個在數據庫中的一個在令牌中?

任何額外的信息,非常感謝。

回答

1
  1. id_token應在客戶端使用。您可以使用它來訪問客戶端的索賠。 AccessToken將在API中使用。

  2. 要將聲明包含在access_token中,您需要創建一個包含相關聲明的作用域並在請求中請求該作用域。 要創建範圍(在self-host sample添加範圍Scopes.cs):

    new Scope 
    { 
          Name = "myApiScope", 
          DisplayName = "IdentityManager", 
          Type = ScopeType.Resource, 
          Emphasize = true, 
          ShowInDiscoveryDocument = false, 
    
          Claims = new List<ScopeClaim> 
          { 
           new ScopeClaim(Constants.ClaimTypes.Name), 
           new ScopeClaim(Constants.ClaimTypes.Role) 
          } 
    } 
    

要求在您的授權請求範圍(在Javascript implicit client - simple是做如下)

function getToken() { 
     var authorizationUrl = 'https://localhost:44333/core/connect/authorize'; 
     var client_id = 'implicitclient'; 
     var redirect_uri = 'http://localhost:37045/index.html'; 
     var response_type = "token"; 
     var scope = "myApiScope"; 
     var state = Date.now() + "" + Math.random(); 

     localStorage["state"] = state; 

     var url = 
      authorizationUrl + "?" + 
      "client_id=" + encodeURI(client_id) + "&" + 
      "redirect_uri=" + encodeURI(redirect_uri) + "&" + 
      "response_type=" + encodeURI(response_type) + "&" + 
      "scope=" + encodeURI(scope) + "&" + 
      "state=" + encodeURI(state); 
     window.location = url; 
    } 

這將包括您的訪問令牌中的名稱和角色聲明

  1. 配置您的在web API啓動時帶有相關中間件的API(SampleAspNetWebApi樣本按如下方式完成)

    app。UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions { Authority =「https://localhost:44333/core」, RequiredScopes = new [] {「myApiScope」} });

然後你就可以訪問索賠如下

  var principal = User as ClaimsPrincipal; 
      return from c in principal.Identities.First().Claims 
        select new 
        { 
         c.Type, 
         c.Value 
        };