基于 JWT 声明授权访问权限

本文介绍 Azure API 管理策略示例,该示例演示如何基于 JWT 声明授予对 API 中特定 HTTP 方法的访问权限。 若要设置或编辑策略代码,请执行设置或编辑策略中所述的步骤。 若要查看其他示例,请参阅策略示例

策略

将代码粘贴到“入站”块中。

<!-- The policy defined in this file shows how to authorize access to specific HTTP methods on an API based on JWT claims. -->
<!-- To test the policy you can use https://jwt.io to generate tokens. -->

<!-- Copy the following snippet into the inbound section. -->

<policies>
  <inbound>
    <base />
      <choose>
        <when condition="@(context.Request.Method.Equals("patch=""",StringComparison.OrdinalIgnoreCase))">
          <validate-jwt header-name="Authorization">
            <issuer-signing-keys>
              <key>{{signing-key}}</key>
            </issuer-signing-keys>
            <required-claims>
              <claim name="edit">
                <value>true</value>
              </claim>
            </required-claims>
          </validate-jwt>
        </when>
        <when condition="@(new [] {"post=""", "put="""}.Contains(context.Request.Method,StringComparer.OrdinalIgnoreCase))">
          <validate-jwt header-name="Authorization">
            <issuer-signing-keys>
              <key>{{signing-key}}</key>
            </issuer-signing-keys>
            <required-claims>
              <claim name="create">
                <value>true</value>
              </claim>
            </required-claims>
          </validate-jwt>
        </when>
        <otherwise>
          <validate-jwt header-name="Authorization">
            <issuer-signing-keys>
              <key>{{signing-key}}</key>
            </issuer-signing-keys>
          </validate-jwt>
        </otherwise>
      </choose>    
  </inbound>
  <backend>
    <base />
  </backend>
  <outbound>
    <base />
  </outbound>
  <on-error>
    <base />
  </on-error>
</policies>

后续步骤

了解有关 APIM 策略的详细信息: