问题描述
在APIM中配置JWT策略,验证JWT,如果认证失败,则跳转到 Azure Entra ID 的 Login 页面。
问题解答
要实现JWT验证失败后,跳转到 Azure Entra ID 的 Login 页面。需要使用到两种策略:
- validate-jwt :https://learn.microsoft.com/en-us/azure/api-management/validate-jwt-policy
- 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&redirect_uri=<redirect_uri>&client_id=<client_id>&scope=openid+profile+email&response_mode=form_post&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&redirect_uri=<redirect_uri>&client_id=<client_id>&scope=openid+profile+email&response_mode=form_post&state=redir%3D%252F</value> </set-header> </return-response> </when> </choose> </on-error> </policies>
注意:在on error部分设置response的Location时候,需要在Login 的URL参数中连接字符(&)需要用HTML编码符标识为 & ,即在HTML中用&表示&符号
测试效果图
参考资料
配置 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