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

发布时间 2024-01-02 21:01:44作者: 路边两盏灯

问题描述

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

 

问题解答

 

主要是需要实现当JWT验证失败后,需要跳转到 Azure Entra ID 的 Login 页面。所以在JWT的策略中,需要在<on-error>部分加入Location Header并指定为Login URL:

示例Policy为:

<policies>
    <inbound>
        <base />
        <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">
            <openid-config url="https://login.partner.microsoftonline.cn/<your tenant id or common>/v2.0/.well-known/openid-configuration" />
            <audiences>
                <audience>aud name</audience>
            </audiences>
        </validate-jwt>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
        <choose>
            <when condition="@(context.LastError.Source == "validate-jwt")">
                <return-response>
                    <set-status code="302" reason="Unauthorized" />
                    <set-header name="Location" exists-action="override">
                        <value>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</value>
                    </set-header>
                </return-response>
            </when>
        </choose>
    </on-error>
</policies>

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

 

测试效果图

 

参考资料