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

问题描述

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

 

问题解答

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

  1. validate-jwt :https://learn.microsoft.com/en-us/azure/api-management/validate-jwt-policy
  2. return-response : https://learn.microsoft.com/en-us/azure/api-management/return-response-policy

并且需要在<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为

<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;表示&符号 

 

测试效果图

 

参考资料

 

posted @ 2024-01-02 21:00  路边两盏灯  阅读(41)  评论(0编辑  收藏  举报