基于 JWT 声明授权访问权限Authorize access based on JWT claims

本文介绍 Azure API 管理策略示例,该示例演示如何基于 JWT 声明授予对 API 中特定 HTTP 方法的访问权限。This article shows an Azure API management policy sample that demonstrates how to authorize access to specific HTTP methods on an API based on JWT claims. 若要设置或编辑策略代码,请执行设置或编辑策略中所述的步骤。To set or edit a policy code, follow the steps described in Set or edit a policy. 若要查看其他示例,请参阅策略示例To see other examples, see policy samples.

策略Policy

将代码粘贴到“入站”块中。Paste the code into the inbound block.

<!-- 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>

后续步骤Next steps

了解有关 APIM 策略的详细信息:Learn more about APIM policies: