2016-09-17 40 views
2

從/令牌的響應返回一個有效載荷,看起來是這樣的:如何重命名Web Api承載令牌「.expires」鍵?

"access_token":"foo", 
"token_type":"bearer", 
"expires_in":59, 
"refresh_token":"bar", 
".issued":"Sat, 17 Sep 2016 00:13:21 GMT", 
".expires":"Sat, 17 Sep 2016 00:14:21 GMT" 

有.issued一個原因,.expired命名他們的方式他們是誰?這些都不是有效的JavaScript屬性,所以我打算重新命名它們。如果有一個更優雅的方式來做到這一點,除了重寫TokenEndpoint方法是這樣的:

public override Task TokenEndpoint(OAuthTokenEndpointContext context) 
{ 
    foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) 
    { 
     string key = property.Key; 
     switch (key) 
     { 
      case ".expires": 
       key = "expires"; 
       break; 
      case ".issued": 
       key = "issued"; 
       break; 
     } 
     context.AdditionalResponseParameters.Add(key, property.Value); 
    } 
    return Task.FromResult<object>(null); 
} 

爲什麼我想要做這樣的一個例子。我喜歡提供一個TypeScript接口,它模仿我期望從請求中獲得的數據。在這種情況下,我的界面看起來是這樣的:

interface IToken { 
    .expires: string;  // Not valid TypeScript 
    .issued: string;   // Not valid TypeScript 
    access_token: string; 
    expires_in: number; 
    token_type: string; 
    refresh_token: string; 
} 

沒有改變我的API的財產,我和使用我的API人被迫訪問諸如tokenVar[".expires"]

回答

1

使用魔法字符串這些屬性我不知道認爲有一個具體的理由來做到這一點。這只是另一個常用的。請參閱此處的AuthenticationProperties.cs https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin/Security/AuthenticationProperties.cs

由於在您的代碼覆蓋TokenEndpoint方法OAuthAuthorizationServerProvider是最好的方法來解決它。

+0

我編輯了我的問題,提供了一個爲什麼我想要這樣做的例子。 –

+0

是的,我瞭解這一部分,但正如我所提到的,重寫'TokenEndpoint'是唯一的方法去做它,你已經在做。 –