【Azure APIM】在APIM中实现JWT验证不通过时跳转到Azure登录页面

问题描述

在APIM中配置JWT策略,验证JWT,如果认证失败,则跳转到 Azure Entra ID 的 Login 页面。

 

问题解答

要实现JWT验证失败后,跳转到 Azure Entra ID 的 Login 页面。需要使用到两种策略:

并且需要在<on-error>部分覆写Location值,指定为Login URL:https://login.partner.microsoftonline.cn/<your tenant id or common>/oauth2/v2.0/authorize?response_type=code+id_token&amp;redirect_uri=<redirect_uri>&amp;client_id=<client_id>&amp;scope=openid+profile+email&amp;response_mode=form_post&amp;state=redir%3D%252F

 

示例Policy为

&lt;policies&gt;
    &lt;inbound&gt;
        &lt;base /&gt;
        &lt;validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="jwt validation failed" require-expiration-time="false" require-scheme="Bearer" require-signed-tokens="true"&gt;
            &lt;openid-config url="https://login.partner.microsoftonline.cn/&lt;your tenant id or common&gt;/v2.0/.well-known/openid-configuration" /&gt;
            &lt;audiences&gt;
                &lt;audience&gt;aud name&lt;/audience&gt;
            &lt;/audiences&gt;
        &lt;/validate-jwt&gt;
    &lt;/inbound&gt;
    &lt;backend&gt;
        &lt;base /&gt;
    &lt;/backend&gt;
    &lt;outbound&gt;
        &lt;base /&gt;
    &lt;/outbound&gt;
    &lt;on-error&gt;
        &lt;base /&gt;
        &lt;choose&gt;
            &lt;when condition="@(context.LastError.Source == "validate-jwt")"&gt;
                &lt;return-response&gt;
                    &lt;set-status code="302" reason="Unauthorized" /&gt;
                    &lt;set-header name="Location" exists-action="override"&gt;
                        &lt;value&gt;https://login.partner.microsoftonline.cn/&lt;your tenant id or common&gt;/oauth2/v2.0/authorize?response_type=code+id_token&amp;amp;redirect_uri=&lt;redirect_uri&gt;&amp;amp;client_id=&lt;client_id&gt;&amp;amp;scope=openid+profile+email&amp;amp;response_mode=form_post&amp;amp;state=redir%3D%252F&lt;/value&gt;
                    &lt;/set-header&gt;
                &lt;/return-response&gt;
            &lt;/when&gt;
        &lt;/choose&gt;
    &lt;/on-error&gt;
&lt;/policies&gt;

注意:在on error部分设置response的Location时候,需要在Login 的URL参数中连接字符(&)需要用HTML编码符标识为 &amp; ,即在HTML中用&amp;表示&符号 

 

测试效果图

 

参考资料

配置 JWT 验证策略,对请求进行预授权:https://docs.azure.cn/zh-cn/api-management/api-management-howto-protect-backend-with-aad#configure-a-jwt-validation-policy-to-pre-authorize-requests

Use custom error messages for jwt-validate policy with on-error : https://github.com/Azure/api-management-policy-snippets/blob/master/examples/Use%20custom%20error%20messages%20for%20jwt-validate%20policy%20with%20on-error%20handler.policy.xml

Request an authorization code : https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-authorization-code 

 

 

 

 

正在加载评论...