您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

API 管理访问限制策略API Management access restriction policies

本主题提供以下 API 管理策略的参考。This topic provides a reference for the following API Management policies. 有关添加和配置策略的信息,请参阅 API 管理中的策略For information on adding and configuring policies, see Policies in API Management.

访问限制策略Access restriction policies

提示

可以在不同的范围内为不同的目的使用访问限制策略。You can use access restriction policies in different scopes for different purposes. 例如,可以通过在 API 级别上应用 validate-jwt 策略来使用 AAD 身份验证保护整个 API,也可以在 API 操作级别上应用它并使用 claims 进行更细粒度的控制。For example, you can secure the whole API with AAD authentication by applying the validate-jwt policy on the API level or you can apply it on the API operation level and use claims for more granular control.

检查 HTTP 标头Check HTTP header

使用 check-header 策略强制请求具有指定的 HTTP 标头。Use the check-header policy to enforce that a request has a specified HTTP header. 可以选择性地查看标头是否具有特定值,或者检查是否存在一系列允许的值。You can optionally check to see if the header has a specific value or check for a range of allowed values. 如果检查失败,此策略会终止请求处理,并返回其所指定的 HTTP 状态代码和错误消息。If the check fails, the policy terminates request processing and returns the HTTP status code and error message specified by the policy.

策略语句Policy statement

<check-header name="header name" failed-check-httpcode="code" failed-check-error-message="message" ignore-case="true">
    <value>Value1</value>
    <value>Value2</value>
</check-header>

示例Example

<check-header name="Authorization" failed-check-httpcode="401" failed-check-error-message="Not authorized" ignore-case="false">
    <value>f6dc69a089844cf6b2019bae6d36fac8</value>
</check-header>

元素Elements

名称Name 说明Description 必须Required
check-headercheck-header 根元素。Root element. Yes
valuevalue 允许的 HTTP 标头值。Allowed HTTP header value. 指定了多个值元素时,如果任何一个值匹配,则检查将被视为成功。When multiple value elements are specified, the check is considered a success if any one of the values is a match. No

属性Attributes

名称Name 说明Description 必须Required 默认Default
failed-check-error-messagefailed-check-error-message 在标头不存在或其值无效的情况下,需要在 HTTP 响应正文中返回的错误消息。Error message to return in the HTTP response body if the header doesn't exist or has an invalid value. 此消息必须对任何特殊字符正确地进行转义。This message must have any special characters properly escaped. Yes 不适用N/A
failed-check-httpcodefailed-check-httpcode 在标头不存在或其值无效时需返回的 HTTP 状态代码。HTTP Status code to return if the header doesn't exist or has an invalid value. Yes 不适用N/A
header-nameheader-name 要检查的 HTTP 标头的名称。The name of the HTTP Header to check. Yes 不适用N/A
ignore-caseignore-case 可以设置为 True 或 False。Can be set to True or False. 如果设置为 True,则在将标头值与一组可接受的值进行比较时,会忽略大小写。If set to True case is ignored when the header value is compared against the set of acceptable values. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站、出站Policy sections: inbound, outbound

  • 策略范围: 所有范围Policy scopes: all scopes

按订阅限制调用速率Limit call rate by subscription

rate-limit 策略可以对调用速率进行限制,使每个指定时段的调用不超出指定的数目,避免单个订阅的 API 使用量暴增。The rate-limit policy prevents API usage spikes on a per subscription basis by limiting the call rate to a specified number per a specified time period. 超过调用速率时,调用方会收到 429 Too Many Requests 响应状态代码。When the call rate is exceeded, the caller receives a 429 Too Many Requests response status code.

重要

每个策略文档只能使用此策略一次。This policy can be used only once per policy document.

策略表达式不能用于此策略的任何策略属性。Policy expressions cannot be used in any of the policy attributes for this policy.

注意

由于限制体系结构的分布式性质,速率限制永远不可能完全准确。Due to the distributed nature of throttling architecture, rate limiting is never completely accurate. 允许的请求的配置数字和实际数字之间的差异因请求量和速度、后端延迟以及其他因素而异。The difference between configured and the real number of allowed requests vary based on request volume and rate, backend latency, and other factors.

备注

若要了解速率限制和配额之间的差异,请参阅速率限制和配额To understand the difference between rate limits and quotas, see Rate limits and quotas.

策略语句Policy statement

<rate-limit calls="number" renewal-period="seconds">
    <api name="API name" id="API id" calls="number" renewal-period="seconds" />
        <operation name="operation name" id="operation id" calls="number" renewal-period="seconds" 
        retry-after-header-name="header name" 
        retry-after-variable-name="policy expression variable name"
        remaining-calls-header-name="header name"  
        remaining-calls-variable-name="policy expression variable name"
        total-calls-header-name="header name"/>
    </api>
</rate-limit>

示例Example

在下面的示例中,每个订阅的速率限制为每 90 秒 20 个调用。In the following example, the per subscription rate limit is 20 calls per 90 seconds. 每次执行策略后,在该时间段内允许的剩余调用存储在变量 remainingCallsPerSubscription 中。After each policy execution, the remaining calls allowed in the time period are stored in the variable remainingCallsPerSubscription.

<policies>
    <inbound>
        <base />
        <rate-limit calls="20" renewal-period="90" remaining-calls-variable-name="remainingCallsPerSubscription"/>
    </inbound>
    <outbound>
        <base />
    </outbound>
</policies>

元素Elements

名称Name 说明Description 必需Required
rate-limitrate-limit 根元素。Root element. Yes
apiapi 添加一个或多个此类元素,对产品中的 API 施加调用速率限制。Add one or more of these elements to impose a call rate limit on APIs within the product. 产品和 API 的调用速率限制是分别应用的。Product and API call rate limits are applied independently. 可以通过 nameid 引用 API。API can be referenced either via name or id. 如果同时提供了这两个属性,则将使用 id 并忽略 nameIf both attributes are provided, id will be used and name will be ignored. No
operationoperation 添加一个或多个此类元素,对 API 中的操作施加调用速率限制。Add one or more of these elements to impose a call rate limit on operations within an API. 产品、API 和操作的调用速率限制是分别应用的。Product, API, and operation call rate limits are applied independently. 可以通过 nameid 引用 Operation。Operation can be referenced either via name or id. 如果同时提供了这两个属性,则将使用 id 并忽略 nameIf both attributes are provided, id will be used and name will be ignored. No

属性Attributes

名称Name 说明Description 必须Required 默认Default
namename 要对其应用速率限制的 API 的名称。The name of the API for which to apply the rate limit. Yes 空值N/A
callscalls renewal-period 所指定的时间间隔内允许的最大总调用数。The maximum total number of calls allowed during the time interval specified in renewal-period. Yes 空值N/A
renewal-periodrenewal-period 滑动窗口的长度(以秒为单位),在此期间,允许的请求数不应超过 calls 中指定的值。The length in seconds of the sliding window during which the number of allowed requests should nor exceed the value specified in calls. Yes 空值N/A
retry-after-header-nameretry-after-header-name 响应头的名称,其值为在超过指定的调用速率后建议的重试间隔(以秒为单位)。The name of a response header whose value is the recommended retry interval in seconds after the specified call rate is exceeded. No 空值N/A
retry-after-variable-nameretry-after-variable-name 策略表达式变量的名称,该变量用于存储在超过指定的调用速率后建议的重试间隔(以秒为单位)。The name of a policy expression variable that stores the recommended retry interval in seconds after the specified call rate is exceeded. No 空值N/A
remaining-calls-header-nameremaining-calls-header-name 响应头的名称,每次执行策略后,其值为在 renewal-period 中指定的时间间隔内允许的剩余调用数。The name of a response header whose value after each policy execution is the number of remaining calls allowed for the time interval specified in the renewal-period. No 空值N/A
remaining-calls-variable-nameremaining-calls-variable-name 策略表达式变量的名称,该变量用于存储在每次执行策略后,renewal-period 中指定的时间间隔内允许的剩余调用数。The name of a policy expression variable that after each policy execution stores the number of remaining calls allowed for the time interval specified in the renewal-period. No 空值N/A
total-calls-header-nametotal-calls-header-name 响应头的名称,其值为 calls 中指定的值。The name of a response header whose value is the value specified in calls. No 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound

  • 策略范围: 产品、API、操作Policy scopes: product, api, operation

按密钥限制调用速率Limit call rate by key

重要

此功能在 API 管理的“消耗”层中不可用。This feature is unavailable in the Consumption tier of API Management.

rate-limit-by-key 策略可以对调用速率进行限制,使指定时段的调用不超出指定的数目,避免单个密钥的 API 使用量暴增。The rate-limit-by-key policy prevents API usage spikes on a per key basis by limiting the call rate to a specified number per a specified time period. 密钥的值可以是任意字符串,通常使用策略表达式来提供密钥。The key can have an arbitrary string value and is typically provided using a policy expression. 可以添加可选增量条件,指定在决定是否到达限制值时应该进行计数的请求。Optional increment condition can be added to specify which requests should be counted towards the limit. 超过此调用速率时,调用方会收到 429 Too Many Requests 响应状态代码。When this call rate is exceeded, the caller receives a 429 Too Many Requests response status code.

有关此策略的详细信息和示例,请参阅使用 Azure API 管理进行高级请求限制For more information and examples of this policy, see Advanced request throttling with Azure API Management.

注意

由于限制体系结构的分布式性质,速率限制永远不可能完全准确。Due to the distributed nature of throttling architecture, rate limiting is never completely accurate. 允许的请求的配置数字和实际数字之间的差异因请求量和速度、后端延迟以及其他因素而异。The difference between configured and the real number of allowed requests vary based on request volume and rate, backend latency, and other factors.

备注

若要了解速率限制和配额之间的差异,请参阅速率限制和配额To understand the difference between rate limits and quotas, see Rate limits and quotas.

策略语句Policy statement

<rate-limit-by-key calls="number"
                   renewal-period="seconds"
                   increment-condition="condition"
                   counter-key="key value" 
                   retry-after-header-name="header name" retry-after-variable-name="policy expression variable name"
                   remaining-calls-header-name="header name"  remaining-calls-variable-name="policy expression variable name"
                   total-calls-header-name="header name"/> 

示例Example

在下面的示例中,可通过调用方 IP 地址对速率限制进行键控,将其控制为 每 60 秒 10 个调用。In the following example, the rate limit of 10 calls per 60 seconds is keyed by the caller IP address. 每次执行策略后,在该时间段内允许的剩余调用存储在变量 remainingCallsPerIP 中。After each policy execution, the remaining calls allowed in the time period are stored in the variable remainingCallsPerIP.

<policies>
    <inbound>
        <base />
        <rate-limit-by-key  calls="10"
              renewal-period="60"
              increment-condition="@(context.Response.StatusCode == 200)"
              counter-key="@(context.Request.IpAddress)"
              remaining-calls-variable-name="remainingCallsPerIP"/>
    </inbound>
    <outbound>
        <base />
    </outbound>
</policies>

元素Elements

名称Name 说明Description 必需Required
rate-limit-by-keyrate-limit-by-key 根元素。Root element. Yes

属性Attributes

名称Name 说明Description 必须Required 默认Default
callscalls renewal-period 所指定的时间间隔内允许的最大总调用数。The maximum total number of calls allowed during the time interval specified in the renewal-period. Yes 空值N/A
counter-keycounter-key 用于速率限制策略的密钥。The key to use for the rate limit policy. Yes 空值N/A
increment-conditionincrement-condition 一个布尔表达式,指定是否应将请求计入速率 (true)。The boolean expression specifying if the request should be counted towards the rate (true). No 空值N/A
renewal-periodrenewal-period 滑动窗口的长度(以秒为单位),在此期间,允许的请求数不应超过 calls 中指定的值。The length in seconds of the sliding window during which the number of allowed requests should nor exceed the value specified in calls. Yes 空值N/A
retry-after-header-nameretry-after-header-name 响应头的名称,其值为在超过指定的调用速率后建议的重试间隔(以秒为单位)。The name of a response header whose value is the recommended retry interval in seconds after the specified call rate is exceeded. No 空值N/A
retry-after-variable-nameretry-after-variable-name 策略表达式变量的名称,该变量用于存储在超过指定的调用速率后建议的重试间隔(以秒为单位)。The name of a policy expression variable that stores the recommended retry interval in seconds after the specified call rate is exceeded. No 空值N/A
remaining-calls-header-nameremaining-calls-header-name 响应头的名称,每次执行策略后,其值为在 renewal-period 中指定的时间间隔内允许的剩余调用数。The name of a response header whose value after each policy execution is the number of remaining calls allowed for the time interval specified in the renewal-period. No 空值N/A
remaining-calls-variable-nameremaining-calls-variable-name 策略表达式变量的名称,该变量用于存储在每次执行策略后,renewal-period 中指定的时间间隔内允许的剩余调用数。The name of a policy expression variable that after each policy execution stores the number of remaining calls allowed for the time interval specified in the renewal-period. No 空值N/A
total-calls-header-nametotal-calls-header-name 响应头的名称,其值为 calls 中指定的值。The name of a response header whose value is the value specified in calls. No 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound

  • 策略范围: 所有范围Policy scopes: all scopes

限制调用方 IPRestrict caller IPs

ip-filter 策略筛选(允许/拒绝)来自特定 IP 地址和/或地址范围的调用。The ip-filter policy filters (allows/denies) calls from specific IP addresses and/or address ranges.

策略语句Policy statement

<ip-filter action="allow | forbid">
    <address>address</address>
    <address-range from="address" to="address" />
</ip-filter>

示例Example

在下面的示例中,策略仅允许来自指定的单一 IP 地址或 IP 地址范围的请求In the following example, the policy only allows requests coming either from the single IP address or range of IP addresses specified

<ip-filter action="allow">
    <address>13.66.201.169</address>
    <address-range from="13.66.140.128" to="13.66.140.143" />
</ip-filter>

元素Elements

名称Name 说明Description 必需Required
ip-filterip-filter 根元素。Root element. Yes
addressaddress 指定要对其进行筛选的单个 IP 地址。Specifies a single IP address on which to filter. 至少一个 addressaddress-range 元素是必需的。At least one address or address-range element is required.
address-range from="address" to="address"address-range from="address" to="address" 指定要对其进行筛选的 IP 地址范围。Specifies a range of IP address on which to filter. 至少一个 addressaddress-range 元素是必需的。At least one address or address-range element is required.

属性Attributes

名称Name 说明Description 必须Required 默认Default
address-range from="address" to="address"address-range from="address" to="address" 允许或拒绝其访问的某个 IP 地址范围。A range of IP addresses to allow or deny access for. 使用 address-range 元素时必需。Required when the address-range element is used. 空值N/A
ip-filter action="allow | forbid"ip-filter action="allow | forbid" 指定是否应允许指定的 IP 地址和范围执行调用。Specifies whether calls should be allowed or not for the specified IP addresses and ranges. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound
  • 策略范围: 所有范围Policy scopes: all scopes

按订阅设置使用量配额Set usage quota by subscription

quota 策略允许根据订阅强制实施可续订或有生存期的调用量和/或带宽配额。The quota policy enforces a renewable or lifetime call volume and/or bandwidth quota, on a per subscription basis.

重要

每个策略文档只能使用此策略一次。This policy can be used only once per policy document.

策略表达式不能用于此策略的任何策略属性。Policy expressions cannot be used in any of the policy attributes for this policy.

备注

若要了解速率限制和配额之间的差异,请参阅速率限制和配额To understand the difference between rate limits and quotas, see Rate limits and quotas.

策略语句Policy statement

<quota calls="number" bandwidth="kilobytes" renewal-period="seconds">
    <api name="API name" id="API id" calls="number" renewal-period="seconds" />
        <operation name="operation name" id="operation id" calls="number" renewal-period="seconds" />
    </api>
</quota>

示例Example

<policies>
    <inbound>
        <base />
        <quota calls="10000" bandwidth="40000" renewal-period="3600" />
    </inbound>
    <outbound>
        <base />
    </outbound>
</policies>

元素Elements

名称Name 说明Description 必需Required
quotaquota 根元素。Root element. Yes
apiapi 添加一个或多个此类元素,对产品中的 API 设置调用配额。Add one or more of these elements to impose call quota on APIs within the product. 产品和 API 的调用配额是分别应用的。Product and API call quotas are applied independently. 可以通过 nameid 引用 API。API can be referenced either via name or id. 如果同时提供了这两个属性,则将使用 id 并忽略 nameIf both attributes are provided, id will be used and name will be ignored. No
operationoperation 添加一个或多个此类元素,对 API 中的操作设置调用配额。Add one or more of these elements to impose call quota on operations within an API. 产品、API 和操作的调用配额是分别应用的。Product, API, and operation call quotas are applied independently. 可以通过 nameid 引用 Operation。Operation can be referenced either via name or id. 如果同时提供了这两个属性,则将使用 id 并忽略 nameIf both attributes are provided, id will be used and name will be ignored. No

属性Attributes

名称Name 说明Description 必须Required 默认Default
namename 要向其应用配额的 API 或操作的名称。The name of the API or operation for which the quota applies. Yes 空值N/A
bandwidthbandwidth renewal-period 所指定的时间间隔内允许的最大总字节数(千字节)。The maximum total number of kilobytes allowed during the time interval specified in the renewal-period. 必须指定 calls 和/或 bandwidthEither calls, bandwidth, or both together must be specified. 空值N/A
callscalls renewal-period 所指定的时间间隔内允许的最大总调用数。The maximum total number of calls allowed during the time interval specified in the renewal-period. 必须指定 calls 和/或 bandwidthEither calls, bandwidth, or both together must be specified. 空值N/A
renewal-periodrenewal-period 在重置配额之前等待的时间长度,以秒为单位。The time period in seconds after which the quota resets. 设置为 0 时,时间段设置为无限。When it's set to 0 the period is set to infinite. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound
  • 策略范围: 产品Policy scopes: product

按密钥设置使用量配额Set usage quota by key

重要

此功能在 API 管理的“消耗”层中不可用。This feature is unavailable in the Consumption tier of API Management.

quota-by-key 策略允许根据密钥强制实施可续订或有生存期的调用量和/或带宽配额。The quota-by-key policy enforces a renewable or lifetime call volume and/or bandwidth quota, on a per key basis. 密钥的值可以是任意字符串,通常使用策略表达式来提供密钥。The key can have an arbitrary string value and is typically provided using a policy expression. 可以添加可选增量条件,指定应在配额范围内的请求。Optional increment condition can be added to specify which requests should be counted towards the quota. 如果多个策略增加相同的键值,则每个请求的键值仅增加一次。If multiple policies would increment the same key value, it is incremented only once per request. 超过调用速率时,调用方会收到 403 Forbidden 响应状态代码。When the call rate is exceeded, the caller receives a 403 Forbidden response status code.

有关此策略的详细信息和示例,请参阅使用 Azure API 管理进行高级请求限制For more information and examples of this policy, see Advanced request throttling with Azure API Management.

备注

若要了解速率限制和配额之间的差异,请参阅速率限制和配额To understand the difference between rate limits and quotas, see Rate limits and quotas.

策略语句Policy statement

<quota-by-key calls="number"
              bandwidth="kilobytes"
              renewal-period="seconds"
              increment-condition="condition"
              counter-key="key value" />

示例Example

在下面的示例中,可通过调用方 IP 地址对配额进行键控。In the following example, the quota is keyed by the caller IP address.

<policies>
    <inbound>
        <base />
        <quota-by-key calls="10000" bandwidth="40000" renewal-period="3600"
                      increment-condition="@(context.Response.StatusCode >= 200 && context.Response.StatusCode < 400)"
                      counter-key="@(context.Request.IpAddress)" />
    </inbound>
    <outbound>
        <base />
    </outbound>
</policies>

元素Elements

名称Name 说明Description 必需Required
quotaquota 根元素。Root element. Yes

属性Attributes

名称Name 说明Description 必须Required 默认Default
bandwidthbandwidth renewal-period 所指定的时间间隔内允许的最大总字节数(千字节)。The maximum total number of kilobytes allowed during the time interval specified in the renewal-period. 必须指定 calls 和/或 bandwidthEither calls, bandwidth, or both together must be specified. 空值N/A
callscalls renewal-period 所指定的时间间隔内允许的最大总调用数。The maximum total number of calls allowed during the time interval specified in the renewal-period. 必须指定 calls 和/或 bandwidthEither calls, bandwidth, or both together must be specified. 空值N/A
counter-keycounter-key 用于配额策略的密钥。The key to use for the quota policy. Yes 空值N/A
increment-conditionincrement-condition 一个布尔表达式,指定是否应将请求计入配额 (true)The boolean expression specifying if the request should be counted towards the quota (true) No 空值N/A
renewal-periodrenewal-period 在重置配额之前等待的时间长度,以秒为单位。The time period in seconds after which the quota resets. 设置为 0 时,时间段设置为无限。When it's set to 0 the period is set to infinite. Yes 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound
  • 策略范围: 所有范围Policy scopes: all scopes

验证 JWTValidate JWT

validate-jwt 策略强制要求从指定 HTTP 标头或指定查询参数提取的 JSON Web 令牌 (JWT) 必须存在且有效。The validate-jwt policy enforces existence and validity of a JSON web token (JWT) extracted from either a specified HTTP Header or a specified query parameter.

重要

validate-jwt 策略要求 exp 注册声明包括在 JWT 令牌中,除非 require-expiration-time 属性已指定并设置为 falseThe validate-jwt policy requires that the exp registered claim is included in the JWT token, unless require-expiration-time attribute is specified and set to false. validate-jwt 策略支持 HS256 和 RS256 签名算法。The validate-jwt policy supports HS256 and RS256 signing algorithms. 对于 HS256,必须在策略中以 base64 编码形式提供内联方式的密钥。For HS256 the key must be provided inline within the policy in the base64 encoded form. 对于 RS256,密钥可以通过 Open ID 配置终结点来提供,或者通过提供包含公钥或公钥的模数指数对的已上传证书的 ID 来提供。For RS256 the key may be provided either via an Open ID configuration endpoint, or by providing the ID of an uploaded certificate that contains the public key or modulus-exponent pair of the public key. validate-jwt 策略通过以下加密算法支持使用对称密钥加密的令牌:A128CBC-HS256、A192CBC-HS384、A256CBC-HS512。The validate-jwt policy supports tokens encrypted with symmetric keys using the following encryption algorithms: A128CBC-HS256, A192CBC-HS384, A256CBC-HS512.

策略语句Policy statement

<validate-jwt
    header-name="name of http header containing the token (use query-parameter-name attribute if the token is passed in the URL)"
    failed-validation-httpcode="http status code to return on failure"
    failed-validation-error-message="error message to return on failure"
    token-value="expression returning JWT token as a string"
    require-expiration-time="true|false"
    require-scheme="scheme"
    require-signed-tokens="true|false"
    clock-skew="allowed clock skew in seconds"
    output-token-variable-name="name of a variable to receive a JWT object representing successfully validated token">
  <openid-config url="full URL of the configuration endpoint, e.g. https://login.constoso.com/openid-configuration" />
  <issuer-signing-keys>
    <key>base64 encoded signing key</key>
    <!-- if there are multiple keys, then add additional key elements -->
  </issuer-signing-keys>
  <decryption-keys>
    <key>base64 encoded signing key</key>
    <!-- if there are multiple keys, then add additional key elements -->
  </decryption-keys>
  <audiences>
    <audience>audience string</audience>
    <!-- if there are multiple possible audiences, then add additional audience elements -->
  </audiences>
  <issuers>
    <issuer>issuer string</issuer>
    <!-- if there are multiple possible issuers, then add additional issuer elements -->
  </issuers>
  <required-claims>
    <claim name="name of the claim as it appears in the token" match="all|any" separator="separator character in a multi-valued claim">
      <value>claim value as it is expected to appear in the token</value>
      <!-- if there is more than one allowed values, then add additional value elements -->
    </claim>
    <!-- if there are multiple possible allowed values, then add additional value elements -->
  </required-claims>
</validate-jwt>

示例Examples

简单的令牌验证Simple token validation

<validate-jwt header-name="Authorization" require-scheme="Bearer">
    <issuer-signing-keys>
        <key>{{jwt-signing-key}}</key>  <!-- signing key specified as a named value -->
    </issuer-signing-keys>
    <audiences>
        <audience>@(context.Request.OriginalUrl.Host)</audience>  <!-- audience is set to API Management host name -->
    </audiences>
    <issuers>
        <issuer>http://contoso.com/</issuer>
    </issuers>
</validate-jwt>

使用 RSA 证书进行令牌验证Token validation with RSA certificate

<validate-jwt header-name="Authorization" require-scheme="Bearer">
    <issuer-signing-keys>
        <key certificate-id="my-rsa-cert" />  <!-- signing key specified as certificate ID, enclosed in double-quotes -->
    </issuer-signing-keys>
    <audiences>
        <audience>@(context.Request.OriginalUrl.Host)</audience>  <!-- audience is set to API Management host name -->
    </audiences>
    <issuers>
        <issuer>http://contoso.com/</issuer>
    </issuers>
</validate-jwt>

Azure Active Directory 令牌验证Azure Active Directory token validation

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.microsoftonline.com/contoso.onmicrosoft.com/.well-known/openid-configuration" />
    <audiences>
        <audience>25eef6e4-c905-4a07-8eb4-0d08d5df8b3f</audience>
    </audiences>
    <required-claims>
        <claim name="id" match="all">
            <value>insert claim here</value>
        </claim>
    </required-claims>
</validate-jwt>

Azure Active Directory B2C 令牌验证Azure Active Directory B2C token validation

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.microsoftonline.com/tfp/contoso.onmicrosoft.com/b2c_1_signin/v2.0/.well-known/openid-configuration" />
    <audiences>
        <audience>d313c4e4-de5f-4197-9470-e509a2f0b806</audience>
    </audiences>
    <required-claims>
        <claim name="id" match="all">
            <value>insert claim here</value>
        </claim>
    </required-claims>
</validate-jwt>

根据令牌声明授予操作访问权限Authorize access to operations based on token claims

以下示例演示了如何使用验证 JWT 策略根据令牌声明值授予操作访问权限。This example shows how to use the Validate JWT policy to authorize access to operations based on token claims value.

<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="group" match="any">
            <value>finance</value>
            <value>logistics</value>
        </claim>
    </required-claims>
</validate-jwt>
<choose>
    <when condition="@(context.Request.Method == "POST" && !((Jwt)context.Variables["jwt"]).Claims["group"].Contains("finance"))">
        <return-response>
            <set-status code="403" reason="Forbidden" />
        </return-response>
    </when>
</choose>

元素Elements

元素Element 说明Description 必需Required
validate-jwtvalidate-jwt 根元素。Root element. Yes
audiencesaudiences 包含一系列可接受且可存在于令牌上的受众声明。Contains a list of acceptable audience claims that can be present on the token. 如果存在多个受众值,则会对每个值进行尝试,直到有一个值成功(如果所有值都试完却没有一个成功,则表明验证失败)。If multiple audience values are present, then each value is tried until either all are exhausted (in which case validation fails) or until one succeeds. 必须指定至少一个受众。At least one audience must be specified. No
issuer-signing-keysissuer-signing-keys 一系列 Base64 编码的安全密钥,用于验证签名的令牌。A list of Base64-encoded security keys used to validate signed tokens. 如果存在多个安全密钥,则会对每个密钥进行尝试,直到所有密钥都试完(这种情况表明验证失败),或者直到有一个密钥成功(这对令牌滚动更新十分有用)。If multiple security keys are present, then each key is tried until either all are exhausted (in which case validation fails) or one succeeds (useful for token rollover). 密钥元素有一个可选的 id 属性,用于与 kid 声明进行比较。Key elements have an optional id attribute used to match against kid claim.

也可以使用以下项提供颁发者签名密钥:Alternatively supply an issuer signing key using:

- 格式 <key certificate-id="mycertificate" /> 中的 certificate-id,用于指定已上传到 API 管理的证书实体的标识符- certificate-id in format <key certificate-id="mycertificate" /> to specify the identifier of a certificate entity uploaded to API Management
- 格式 <key n="<modulus>" e="<exponent>" /> 中的 RSA 模数 n 和指数 e 对,用于以 base64url 编码格式指定 RSA 参数- RSA modulus n and exponent e pair in format <key n="<modulus>" e="<exponent>" /> to specify the RSA parameters in base64url-encoded format
No
decryption-keysdecryption-keys 用于解密令牌的 Base64 编码密钥列表。A list of Base64-encoded keys used to decrypt the tokens. 如果存在多个安全密钥,则会对每个密钥进行尝试,直到所有密钥都试完(这种情况表明验证失败)或直到有一个密钥成功为止。If multiple security keys are present, then each key is tried until either all keys are exhausted (in which case validation fails) or a key succeeds. 密钥元素有一个可选的 id 属性,用于与 kid 声明进行比较。Key elements have an optional id attribute used to match against kid claim.

也可以使用以下项提供解密密钥:Alternatively supply a decryption key using:

- 格式 <key certificate-id="mycertificate" /> 中的 certificate-id,用于指定已上传到 API 管理的证书实体的标识符- certificate-id in format <key certificate-id="mycertificate" /> to specify the identifier of a certificate entity uploaded to API Management
No
issuersissuers 一系列可接受的、已颁发了令牌的主体。A list of acceptable principals that issued the token. 如果存在多个颁发者值,则会对每个值进行尝试,直到有一个值成功(如果所有值都试完却没有一个成功,则表明验证失败)。If multiple issuer values are present, then each value is tried until either all are exhausted (in which case validation fails) or until one succeeds. No
openid-configopenid-config 一个元素,用于指定兼容的 Open ID 配置终结点,以便从该终结点获取签名密钥和颁发者。The element used for specifying a compliant Open ID configuration endpoint from which signing keys and issuer can be obtained. No
required-claimsrequired-claims 包含一系列应存在于令牌上的声明,否则令牌会被视为无效。Contains a list of claims expected to be present on the token for it to be considered valid. match 属性设置为 all 时,策略中的每个声明值都必须存在于令牌中,这样验证才会成功。When the match attribute is set to all every claim value in the policy must be present in the token for validation to succeed. match 属性设置为 any 时,至少一个声明必须存在于令牌中,这样验证才会成功。When the match attribute is set to any at least one claim must be present in the token for validation to succeed. No

属性Attributes

名称Name 说明Description 必须Required 默认Default
clock-skewclock-skew 时间跨度。Timespan. 用于指定令牌颁发者的系统时钟与 API 管理实例之间的最大预期时间差。Use to specify maximum expected time difference between the system clocks of the token issuer and the API Management instance. No 0 秒0 seconds
failed-validation-error-messagefailed-validation-error-message JWT 未通过验证时会在 HTTP 响应正文中返回的错误消息。Error message to return in the HTTP response body if the JWT does not pass validation. 此消息必须对任何特殊字符正确地进行转义。This message must have any special characters properly escaped. No 默认错误消息取决于验证问题,例如“JWT 不存在”。Default error message depends on validation issue, for example "JWT not present."
failed-validation-httpcodefailed-validation-httpcode JWT 未通过验证时会返回的 HTTP 状态代码。HTTP Status code to return if the JWT doesn't pass validation. No 401401
header-nameheader-name 包含令牌的 HTTP 标头的名称。The name of the HTTP header holding the token. 必须指定 header-namequery-parameter-nametoken-value 中的一个。One of header-name, query-parameter-name or token-value must be specified. 不适用N/A
query-parameter-namequery-parameter-name 包含令牌的查询参数的名称。The name of the query parameter holding the token. 必须指定 header-namequery-parameter-nametoken-value 中的一个。One of header-name, query-parameter-name or token-value must be specified. 空值N/A
token-valuetoken-value 一个表达式,返回的字符串包含 JWT 令牌Expression returning a string containing JWT token 必须指定 header-namequery-parameter-nametoken-value 中的一个。One of header-name, query-parameter-name or token-value must be specified. 不适用N/A
idid 使用 key 元素的 id 属性可以指定一个字符串,该字符串将与令牌中的 kid 声明(如果存在)进行比较,以便找出进行签名验证时需要使用的适当密钥。The id attribute on the key element allows you to specify the string that will be matched against kid claim in the token (if present) to find out the appropriate key to use for signature validation. No 空值N/A
matchmatch claim 元素的 match 属性用于指定:是否策略中的每个声明值都必须存在于令牌中验证才会成功。The match attribute on the claim element specifies whether every claim value in the policy must be present in the token for validation to succeed. 可能的值为:Possible values are:

- all - 策略中的每个声明值都必须存在于令牌中验证才会成功。- all - every claim value in the policy must be present in the token for validation to succeed.

- any - 至少一个声明值必须存在于令牌中验证才会成功。- any - at least one claim value must be present in the token for validation to succeed.
No allall
require-expiration-timerequire-expiration-time 布尔值。Boolean. 指定令牌中是否需要到期声明。Specifies whether an expiration claim is required in the token. No true
require-schemerequire-scheme 令牌方案的名称,例如“Bearer”。The name of the token scheme, e.g. "Bearer". 设置了此属性时,策略将确保 Authorization 标头值中存在指定的方案。When this attribute is set, the policy will ensure that specified scheme is present in the Authorization header value. No 空值N/A
require-signed-tokensrequire-signed-tokens 布尔值。Boolean. 指定令牌是否需要签名。Specifies whether a token is required to be signed. No true
separatorseparator 字符串。String. 指定要用于从多值声明中提取一组值的分隔符(例如 ",")。Specifies a separator (e.g. ",") to be used for extracting a set of values from a multi-valued claim. No 空值N/A
urlurl Open ID 配置终结点 URL,可以从其获取 Open ID 配置元数据。Open ID configuration endpoint URL from where Open ID configuration metadata can be obtained. 响应应符合以下 URL 中定义的规范:https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadataThe response should be according to specs as defined at URL:https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata. 对于 Azure Active Directory,请使用以下 URL:https://login.microsoftonline.com/{tenant-name}/.well-known/openid-configuration,代之以目录租户名称,例如 contoso.onmicrosoft.comFor Azure Active Directory use the following URL: https://login.microsoftonline.com/{tenant-name}/.well-known/openid-configuration substituting your directory tenant name, e.g. contoso.onmicrosoft.com. Yes 空值N/A
output-token-variable-nameoutput-token-variable-name 字符串。String. 成功进行令牌验证后,将作为 Jwt 类型的对象接收令牌值的上下文变量的名称Name of context variable that will receive token value as an object of type Jwt upon successful token validation No 空值N/A

使用情况Usage

此策略可在以下策略范围中使用。This policy can be used in the following policy sections and scopes.

  • 策略节: 入站Policy sections: inbound
  • 策略范围: 所有范围Policy scopes: all scopes

后续步骤Next steps

有关如何使用策略的详细信息,请参阅:For more information working with policies, see: