【问题标题】:Using azure API management restrict the api call based on the JWT token claim使用 azure API 管理根据 JWT 令牌声明限制 api 调用
【发布时间】:2020-09-24 18:02:46
【问题描述】:

我的项目使用 api 管理服务作为 azure APIM。我正在尝试使用 APIM 产品政策验证声明。如果声明无效,则返回错误,否则允许访问端点。以下是我的政策

   <policies> <inbound> <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    ------------
    ------------ 
</validate-jwt> 
<choose> 
<when condition="@(context.Request.Method != "POST" && ((Jwt)context.Request.Headers["Authorization"].Claims["role"]!= "Owner") && (string)context.Api.Path =="/api/user"> 
<return-response>
 <set-status code="403" reason="Forbidden" />
</return-response>
 </when> </choose>
<base /> 


 </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </policies>

但是即使角色不是所有者用户也可以访问 /api/user 路径 如何正确验证?

JWT calims are
 "userrole": "[Owner,Admin]",
 "email": "test@gmail.com"

【问题讨论】:

  • 如果对你有帮助,欢迎采纳。

标签: azure azure-api-management


【解决方案1】:

此示例展示了如何使用验证 JWT 政策授权访问操作基于令牌声明值

<validate-jwt header-name="Authorization" require-scheme="Bearer" output-token-variable-name="jwt">
    <issuer-signing-keys>
        <key>{{jwt-signing-key}}</key> <!-- signing key is stored in a named value -->
    </issuer-signing-keys>
    <audiences>
        <audience>@(context.Request.OriginalUrl.Host)</audience>
    </audiences>
    <issuers>
        <issuer>contoso.com</issuer>
    </issuers>
    <required-claims>
        <claim name="userrole" match="any">
            <value>Owner</value>
            <value>Admin</value>
        </claim>
    </required-claims>
</validate-jwt>
<choose>
    <when condition="@(context.Request.Method == "POST" && !((Jwt)context.Variables["jwt"]).Claims["group"].Contains("Owner"))">
        <return-response>
            <set-status code="403" reason="Forbidden" />
        </return-response>
    </when>
</choose>

更多详情可以参考这个article

【讨论】:

  • userrole 不是一个单一的值。在声明它的字符串时,它包含“[Owner,Admin]”。要求 calim 只接受完全匹配,对吗?
  • 什么是 jwt-signing-key ?
  • 出现错误找不到属性'jwt-signing-key'
  • 用于验证签名令牌的 Base64 编码安全密钥列表。如果您没有 jwt-signing-key,则可以将其删除,因为它不是必需的。
  • 如果您想同时拥有和管理令牌以进行验证,您可以将匹配设置为all
猜你喜欢
  • 1970-01-01
  • 2015-07-03
  • 2017-11-16
  • 2017-03-15
  • 2015-05-27
  • 2019-07-16
  • 2018-09-13
  • 2014-12-17
  • 1970-01-01
相关资源
最近更新 更多