2017-06-12 78 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流程以了解哪些请求已完成以及接收了哪些响应以及令牌在哪里将是有益的。毕竟众所周知,可以在策略中复制客户端行为以获取令牌。 –

相关问题