2017-06-12 76 views
0

我有一個API應用程序(比如計算器)我使用Portal啓用了AD身份驗證。我將Calculator API添加到API管理服務中。現在我想獲得OAuth令牌來調用Calculator API。我看了這個post如何在API管理服務中使用Oauth連接Azure AD經過身份驗證的API

在上面的帖子裏提到,先獲得授權碼&然後得到令牌。我已經使所有的AAD應用程序&得到了管理員的同意。

在APIM我寫了一個政策,以獲取授權碼

<send-request mode="new" response-variable-name="responseObject" timeout="20" ignore-error="true"> <set-url>@("{{frontAuthServer}}?client_id={{clientId}}&response_type=code&redirect_uri={{FrontredirectUri}}&response_mode=query&resource={{scope}}")</set-url> <set-method>GET</set-method> </send-request> <return-response response-variable-name="existing response variable"> <set-status code="200" reason="OK" /> <set-header name="Content-Type" exists-action="override"> <value>application/json</value> </set-header> <set-body> @(new JObject(new JProperty("code",((IResponse)context.Variables["code"]).Body.As<JObject>())).ToString()) </set-body> </return-response>

但不幸的是授權碼來作爲查詢參數響應&我不能使用策略進行檢索。 所以我只想知道我是否進入正確的方向,如果是,那麼如何從響應中檢索查詢參數? 或者哪種方法可以做到這一點? 我遵循同樣的方式mentioned here

但沒有運氣。任何設置需要做什麼?我錯過了什麼嗎?

回答

0

如果你的目標是在內部策略中流動,使得你的api可以在沒有oauth標記的情況下被調用 - 那麼你就在正確的道路上。如果身份驗證令牌作爲查詢參數發送,那麼您從服務器獲得的內容應該是302位置標頭響應。這樣做如下:

<send-request mode="new" response-variable-name="responseObject" timeout="20" ignore-error="true"> 
    <set-url>@("{{frontAuthServer}}?client_id={{clientId}}&response_type=code&redirect_uri={{FrontredirectUri}}&response_mode=query&resource={{scope}}")</set-url> 
    <set-method>GET</set-method> 
</send-request> 

<set-variable name="token" value="@{ 
    var location = ((IResponse)responseObject).Headers.GetValueOrDefault("Location"); 
    if (string.IsNullOrEmpty(location)) { 
     return null; 
    } 

    var tokenStart = location.IndexOf("token="); 
    if (tokenStart >= 0) { 
     tokenStart += 6; 
     var tokenEnd = location.IndexOf("&", tokenStart); 
     if (tokenEnd < 0) { 
      tokenEnd = location.Length; 
     } 

     return location.Substring(tokenStart, tokenEnd - tokenStart); 
    } 
    return null; 
}" /> 

該令牌之後應該是在一個名爲政策表述爲context.Variables「令牌」訪問[「令牌」]變量。

+0

我做了一些修改。我把var location =((IResponse)context.Variables [「responseObject」])。Headers.GetValueOrDefault(「Location」);獲取位置。它返回null。 –

+0

我沒有得到302.總是得到200. –

+0

使用像Fiddler這樣的工具來跟蹤整個OAuth流程以瞭解哪些請求已完成以及接收了哪些響應以及令牌在哪裏將是有益的。畢竟衆所周知,可以在策略中複製客戶端行爲以獲取令牌。 –

相關問題