是否可针对订阅限制Azure API Management的特定端点访问权限?
解答
完全可以实现,你可以通过Azure API Management的入站策略规则,实现订阅级的单API端点粒度访问控制,具体操作如下:
- 首先给需要做端点限制的订阅配置自定义属性:进入APIM订阅管理页,打开对应订阅的编辑界面,添加自定义属性,例如属性名设为
AllowedEndpoints,属性值填写允许该订阅访问的端点路径,多个路径用英文逗号分隔即可。 - 然后给目标API配置入站校验策略:进入对应API的「策略」编辑界面,添加入站校验逻辑,核心是先获取当前请求关联的订阅的
AllowedEndpoints属性,再对比当前请求的路径是否在允许列表内,不符合就直接返回403拒绝访问。
参考策略示例如下:
<policies> <inbound> <base /> <!-- 提取当前订阅的AllowedEndpoints自定义属性 --> <set-variable name="allowedEndpoints" value="@(context.Subscription?.GetValue<string>("AllowedEndpoints", ""))" /> <!-- 提取当前请求的相对路径 --> <set-variable name="requestPath" value="@(context.Request.Url.Path)" /> <!-- 校验路径是否在允许列表内 --> <choose> <when condition="@(!string.IsNullOrEmpty((string)context.Variables["allowedEndpoints"]) && !((string)context.Variables["allowedEndpoints"]).Split(',').Contains((string)context.Variables["requestPath"]))"> <return-response> <set-status code="403" reason="Forbidden" /> <set-body>当前订阅无权限访问该端点</set-body> </return-response> </when> </choose> </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </on-error> </policies>
补充说明
- 如果需要同时限制HTTP请求方法(比如只允许GET请求某端点),可以在判断逻辑里额外加入
context.Request.Method的匹配规则即可。 - 不需要做端点限制的订阅无需添加
AllowedEndpoints属性,策略默认会直接放行,不会影响原有订阅的正常访问。 - 该能力是APIM原生提供的标准策略能力,不需要额外开通其他服务,也没有额外费用。
内容的提问来源于stack exchange,提问作者Developer Guy
相关产品推荐
相关产品推荐

