2014-12-03 259 views
7

使用思維JWT認證資源所有者流程,我使用JWT的聲明部分來進行客戶端消費。 我的問題是,如果它有可能在身份服務器中添加聲明並將其解碼爲客戶端中的數組。向數組添加聲明給JWT?

數組類型沒有ClaimTypeValues。

作爲一種變通方法,

var user = IdentityServerPrincipal.Create(response.UserName, response.UserName); 
       user.Identities.First().AddClaims(
              new List<Claim>() 
             { 
              new Claim(ClaimTypes.Name, response.UserName), 
              new Claim(ClaimTypes.Email, response.Email), 
              new Claim(FullName, response.FullName), 
              new Claim(AuthorizedCompanies,JsonConvert.SerializeObject(response.AuthorizedCompanies)) 
             }); 
       return new AuthenticateResult(user); 

我添加權利要求作爲JSON數組權利要求爲AuthorizedCompanies和在客戶端side.What解析它是設計圖案這裏如果有的話?

回答

11

從個人經驗來看,當ValueType始終輸入「String」時,與索賠存儲庫進行交互操作會更容易。雖然當你知道你正在處理一個複雜的類型時,它可能看起來並不直觀,但它至少很容易理解。

我已經接觸到這種數組需求的方式是讓我的應用程序代碼預期有多個聲明出現在所討論的聲明類型中,並且保留每個聲明值的簡單類型。

Examp:

var authorizeCompanies = identity.FindAll(AuthorizedCompanies).Select(c => c.Value); 

和當然,你還可以添加他們的方式:

identity.AddClaim(ClaimTypes.Name, response.UserName); 
identity.AddClaim(AuthorizedCompanies, "CompanyX"); 
identity.AddClaim(AuthorizedCompanies, "CompanyY"); 
identity.AddClaim(AuthorizedCompanies, "CompanyZ"); 

IdentityServer支持這種模式的開箱。爲這樣的標識生成標記時,它會自動將該聲明的值作爲數組寫入。

{ 
    "aud": "Identity Server example/resources", 
    "iss": "Identity Server example", 
    "exp": 1417718816, 
    "sub": "1234", 
    "scope": ["read", "write"], // <-- HERE 
    "foo": ["bar", "baz"],  // <-- HERE TOO! 
    "nbf": 1417632416 
} 

這種索賠方法與假設所有索賠是類型 - >值的一對一映射形成對比。