GenerateJWT 政策

您正在查看 Apigee Edge 文档。
前往 Apigee X 文档。
信息

内容

生成一个已签名的 JWT,其中包含一组可配置的声明。那么,JWT 可返回到客户端,传输到后端目标,或以其他方式使用。如需查看详细介绍,请参阅 JWS 和 JWT 政策概览。

视频

观看视频短片,了解如何生成已签名的 JWT。

示例

生成使用 HS256 算法签名的 JWT

此政策示例会生成新的 JWT 并使用 HS256 算法为其签名。HS256 依赖共享密钥来签署和验证签名。

当触发此政策操作时,Edge 会编码 JWT 标头和载荷,然后以数字签署 JWT。请观看上方视频,了解完整示例(包括如何向政策发出请求)。

此处的政策配置将创建 JWT,其中包含一组标准声明(由 JWT 规范定义),其中包括 1 小时的过期时间以及附加声明。您可以根据需要添加任意数量的其他声明。请参阅“元素参考”,详细了解此示例政策中每个元素的要求和选项。

<GenerateJWT name="JWT-Generate-HS256">
    <DisplayName>JWT Generate HS256</DisplayName>
    <Algorithm>HS256</Algorithm>
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    <SecretKey>
        <Value ref="private.secretkey"/>
        <Id>1918290</Id>
    </SecretKey>
    <ExpiresIn>1h</ExpiresIn>
    <Subject>monty-pythons-flying-circus</Subject>
    <Issuer>urn://apigee-edge-JWT-policy-test</Issuer>
    <Audience>fans</Audience>
    <Id/>
    <AdditionalClaims>
        <Claim name="show">And now for something completely different.</Claim>
    </AdditionalClaims>
    <OutputVariable>jwt-variable</OutputVariable>
</GenerateJWT>

生成的 JWT 将具有此标头 …

{
  "typ" : "JWT", 
  "alg" : "HS256",
  "kid" : "1918290"
}

… 并且将包含内容如下的载荷:

{ 
  "sub" : "monty-pythons-flying-circus",
  "iss" : "urn://apigee-edge-JWT-policy-test",
  "aud" : "show",
  "iat" : 1506553019,
  "exp" : 1506556619,
  "jti" : "BD1FF263-3D25-4593-A685-5EC1326E1F37",
  "show": "And now for something completely different."
}

iat、exp 和 jti 声明的值会有所不同。

生成使用 RS256 算法签名的 JWT

此政策示例会生成新的 JWT 并使用 RS256 算法为其签名。生成 RS256 签名依赖于 RSA 私钥,此私钥必须以 PEM 编码格式提供。请观看上方视频,了解完整示例(包括如何向政策发出请求)。

当触发此政策操作时,Edge 会对 JWT(包括声明)进行编码和数字签名。如需了解 JWT 各部分及其加密和签名的方式,请参阅 RFC7519。

<GenerateJWT name="JWT-Generate-RS256">
    <Algorithm>RS256</Algorithm>
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    <PrivateKey>
        <Value ref="private.privatekey"/>
        <Password ref="private.privatekey-password"/>
        <Id ref="private.privatekey-id"/>
    </PrivateKey>
    <Subject>apigee-seattle-hatrack-montage</Subject>
    <Issuer>urn://apigee-edge-JWT-policy-test</Issuer>
    <Audience>urn://c60511c0-12a2-473c-80fd-42528eb65a6a</Audience>
    <ExpiresIn>60m</ExpiresIn>
    <Id/>
    <AdditionalClaims>
        <Claim name="show">And now for something completely different.</Claim>
    </AdditionalClaims>
    <OutputVariable>jwt-variable</OutputVariable>
</GenerateJWT>

设置密钥元素

您用来指定用于生成 JWT 的密钥的元素取决于所选算法,如下表所示:

算法 密钥元素
HS{256/384/512}*
<SecretKey>
  <Value ref="private.secretkey"/>
  <Id>1918290</Id>
</SecretKey>
RS/PS/ES{256/384/512}*
<PrivateKey>
  <Value ref="private.privatekey"/>
  <Password ref="private.privatekey-password"/>
  <Id ref="private.privatekey-id"/>
</PrivateKey>

<Password> 和 <Id> 元素是可选的。

*如需详细了解密钥要求,请参阅签名加密算法简介。

生成 JWT 的元素参考

政策参考介绍了“生成 JWT”政策的元素和属性。

注意:配置因您使用的加密算法而有些许差异。如需查看演示特定用例配置的示例,请参阅示例。

适用于顶级元素的属性

<GenerateJWT name="JWT" continueOnError="false" enabled="true" async="false">

以下属性是所有政策的父级元素都具有的属性。

属性 说明 默认 状态
name 政策的内部名称。您可以在名称中使用的字符仅限于 A-Z0-9._\-$ %。不过,Edge 管理界面会强制执行其他限制,例如自动移除非字母数字字符。

(可选)使用 <displayname></displayname> 元素在管理界面代理编辑器中给政策添加不同的自然语言名称标签。

不适用 必需
continueOnError 设置为 false 可在政策失败时返回错误。对于大多数政策来说,这一行为符合预期。

设置为 true,即使在政策失败后,仍可以继续实施流执行。

false 可选
已启用 设置为 true 可实施政策。

设置为 false 可“关闭”政策。即使政策仍附加到某个流,也不会实施该政策。

true 可选
异步 此属性已弃用。 false 已弃用

<DisplayName>

<DisplayName>Policy Display Name</DisplayName>

除了用于名称属性之外,还可以用于在管理界面代理编辑器中给政策添加不同的自然语言名称标签。

默认 如果省略此元素,则会使用政策的名称属性的值。
状态 可选
类型 字符串

<Algorithm>

<Algorithm>algorithm-here</Algorithm>

指定用于签署令牌的加密算法。

默认 不适用
状态 需要
类型 字符串
有效值 HS256、HS384、HS512、RS256、RS384、RS512、ES256、ES384、ES512、PS256、PS384、PS512

<Audience>

<Audience>audience-here</Audience>

or:

<Audience ref='variable_containing_audience'/>

该政策会生成一个 JWT,其中包含设置为特定值的 aud 声明。此声明标识 JWT 的目标接收者。这是 RFC7519 中所述的一种已注册声明。

默认 不适用
状态 可选
类型 数组(以英文逗号分隔的值列表)
有效值 任何标识受众群体的内容。

<AdditionalClaims/Claim>

<AdditionalClaims>
    <Claim name='claim1'>explicit-value-of-claim-here</Claim>
    <Claim name='claim2' ref='variable-name-here'/>
    <Claim name='claim3' ref='variable-name-here' type='boolean'/>
</AdditionalClaims>

or:

<AdditionalClaims ref='claim_payload'/>

让您可在 JWT 载荷中指定其他声明名称/值对。您可以将声明显式指定为字符串、数字、布尔值、映射或数组。映射只是一组名称/值对。

默认 不适用
状态 可选
有效值 要用于附加声明的任何值。您可以将声明显式指定为字符串、数字、布尔值、映射或数组。

<Claim> 元素具有以下属性:

  • 名称 -(必需)声明的名称。
  • ref -(可选)流变量的名称。如果存在,该政策将使用此变量的值作为声明。如果同时指定了 ref 属性值和明确的声明值,则明确的值则为默认值,并且在引用的流变量未解析的情况下,将使用该值。
  • 类型 -(可选)以下任一项:字符串(默认)、数字、布尔值或映射
  • 数组 -(可选)设置为 true 可指示值是否为类型数组。默认值:false。

添加 <Claim> 元素时,系统会在配置政策时静态设置声明名称。或者,您可以传递 JSON 对象来指定声明名称。由于 JSON 对象是作为变量传递的,因此生成的 JWT 中的声明名称是在运行时确定的。

例如:

<AdditionalClaims ref='json_claims'/>

其中,变量 json_claims 包含采用以下格式的 JSON 对象:

{
  "sub" : "person@example.com",
  "iss" : "urn://secure-issuer@example.com",
  "non-registered-claim" : {
    "This-is-a-thing" : 817,
    "https://example.com/foobar" : { "p": 42, "q": false }
  }
}

生成的 JWT 包含 JSON 对象中的所有声明。

<AdditionalHeaders/Claim>

<AdditionalHeaders>
    <Claim name='claim1'>explicit-value-of-claim-here</Claim>
    <Claim name='claim2' ref='variable-name-here'/>
    <Claim name='claim3' ref='variable-name-here' type='boolean'/>
    <Claim name='claim4' ref='variable-name' type='string' array='true'/>
 </AdditionalHeaders>

在 JWT 的标头中放置额外的声明名称/值对。

默认 不适用
状态 可选
有效值 要用于附加声明的任何值。您可以将声明显式指定为字符串、数字、布尔值、映射或数组。

<Claim> 元素具有以下属性:

  • 名称 -(必需)声明的名称。
  • ref -(可选)流变量的名称。如果存在,该政策将使用此变量的值作为声明。如果同时指定了 ref 属性值和明确的声明值,则明确的值则为默认值,并且在引用的流变量未解析的情况下,将使用该值。
  • 类型 -(可选)以下任一项:字符串(默认)、数字、布尔值或映射
  • 数组 -(可选)设置为 true 可指示值是否为类型数组。默认值:false。

<CriticalHeaders>

<CriticalHeaders>a,b,c</CriticalHeaders>

or:

<CriticalHeaders ref=’variable_containing_headers’/>

将关键标头 crit 添加到 JWT 标头。crit 标头是必须已知且 JWT 接收者可识别的标头名称数组。例如:

{
  “typ: “...”,
  “alg” : “...”,
  “crit” : [ “a”, “b”, “c” ],
}

在运行时,VerifyJWT 政策会检查 crit 标头。对于 crit 标头中列出的每个项,它会检查 VerifyJWT 政策的 <KnownHeaders> 元素也会列出该标头。VerifyJWT 政策在 crit 中找到的任何未在 <KnownHeaders> 中列出的标头都会导致 VerifyJWT 政策失败。

默认 不适用
状态 可选
类型 以逗号分隔的字符串数组
有效值 数组或包含该数组的变量名称。

<CustomClaims>

注意:目前,当您通过界面添加新的 GenerateJWT 政策时,系统会插入 CustomClaims 元素。该元素不起作用,忽略即可。请改用正确的元素,即 <AdditionalClaims>。界面将进行更新,以便稍后插入正确的元素。

<ExpiresIn>

<ExpiresIn>time-value-here</ExpiresIn>

指定 JWT 的生命周期,以毫秒、秒、分钟、小时或天为单位。

默认 N/A
状态 可选
类型 整数
有效值

值或对包含该值的流变量的引用。时间单位可以按如下方式指定:

  • ms = 毫秒(默认)
  • s = 秒
  • m = 分钟
  • h = 小时
  • d = 天

例如,ExpiresIn=10d 等同于 864000s 的 ExpiresIn。

<Id>

<Id>explicit-jti-value-here</Id>
 -or-
<Id ref='variable-name-here'/>
 -or-
<Id/>

使用特定的 jti 声明生成 JWT。当文本值和 ref 属性都为空时,该政策将生成一个包含随机 UUID 的 jti。JWT ID (jti) 声明是 JWT 的唯一标识符。如需详细了解 jti,请参阅 RFC7519。

默认 不适用
状态 可选
类型 字符串或引用。
有效值 字符串或包含 ID 的流变量的名称。

<IgnoreUnresolvedVariables>

<IgnoreUnresolvedVariables>true|false</IgnoreUnresolvedVariables>

如果您希望在无法解析政策中指定的任何引用变量时让政策抛出一个错误,请设置为 false。设置为 true 可将所有无法解析的变量都视为空字符串 (null)。

默认 False
状态 可选
类型 布尔值
有效值 true 或 false

<Issuer>

<Issuer ref='variable-name-here'/>
<Issuer>issuer-string-here</Issuer>

该政策会生成一个 JWT,其中包含名为 iss 的声明,并将值设置为指定值。用于识别 JWT 颁发者的声明。这是 RFC7519 中所述的一组已注册声明组。

默认 不适用
状态 可选
类型 字符串或引用
有效值 不限

<NotBefore>

<!-- Specify an absolute time. -->
<NotBefore>2017-08-14T11:00:21-07:00</NotBefore>
 -or-
<!-- Specify a time relative to when the token is generated. -->
<NotBefore>6h</NotBefore>

指定令牌生效的时间。令牌在指定时间之前无效。您可以指定绝对时间值,也可以指定一个相对于令牌生成时间的时间。

默认 不适用
状态 可选
类型 字符串
有效值 请参阅下文。

绝对时间值的 NotBefore 元素的有效时间值

名称 格式 示例
可排序 yyyy-MM-dd'T'HH:mm:ss.SSSZ 2017-08-14T11:00:21.269-0700
RFC 1123 EEE, dd MMM yyyy HH:mm:ss zzz 美国太平洋夏令时 2017 年 8 月 14 日星期一 11:00:21
RFC 850 EEEE, dd-MMM-yy HH:mm:ss zzz 美国太平洋夏令时 2017 年 8 月 14 日 11:00:21
ANCI-C EEE MMM d HH:mm:ss yyyy 2017 年 8 月 14 日星期一 11:00:21

对于相对时间值,指定整数和时间段,例如:

  • 10 秒
  • 60m
  • 12 小时

<OutputVariable>

<OutputVariable>jwt-variable</OutputVariable>

指定此政策生成的 JWT 的放置位置。默认情况下,它会被放入流变量 jwt.POLICYNAME.generated_jwt。

默认 jwt.POLICYNAME.generated_jwt
状态 可选
类型 字符串(流变量名称)

<PrivateKey/Id>

<PrivateKey>
  <Id ref="flow-variable-name-here"/>
</PrivateKey>

or

<PrivateKey>
  <Id>your-id-value-here</Id>
</PrivateKey>

指定要包含在 JWT 标头中的密钥 ID (kid)。仅在算法是 RS256/RS384/RS512、PS256/PS384/PS512 或 ES256/ES384/ES512 之一时使用。

默认 不适用
状态 可选
类型 字符串
有效值 流变量或字符串

<PrivateKey/Password>

<PrivateKey>
  <Password ref="private.privatekey-password"/>
</PrivateKey>

根据需要指定政策应用来解密私钥的密码。使用 ref 属性在流变量中传递密钥。仅在算法是 RS256/RS384/RS512、PS256/PS384/PS512 或 ES256/ES384/ES512 之一时使用。

默认 不适用
状态 可选
类型 字符串
有效值 流变量引用。

注意:您必须指定流变量。如果政策配置中的密码采用明文形式指定,Edge 会拒绝该配置并将其视为无效配置。流变量的前缀必须为“private”。例如 private.mypassword

<PrivateKey/Value>

<PrivateKey>
  <Value ref="private.variable-name-here"/>
</PrivateKey>

指定用于为 JWT 签名的 PEM 编码私钥。使用 ref 属性在流变量中传递密钥。仅在算法是 RS256/RS384/RS512、PS256/PS384/PS512 或 ES256/ES384/ES512 之一时使用。

默认 不适用
状态 需要使用 RS256 算法生成 JWT。
Type 字符串
有效值 包含 PEM 编码 RSA 私钥值的字符串的流变量。

注意:流变量的前缀必须为“private”。例如,private.mykey

<SecretKey/Id>

<SecretKey>
  <Id ref="flow-variable-name-here"/>
</SecretKey>

or

<SecretKey>
  <Id>your-id-value-here</Id>
</SecretKey>

指定要包含在使用 HMAC 算法签名的 JWT 的 JWT 标头中的密钥 ID (kid)。仅在算法是 HS256/HS384/HS512 之一时使用。

默认 不适用
状态 可选
类型 字符串
有效值 流变量或字符串

<SecretKey/Value>

<SecretKey>
  <Value ref="private.your-variable-name"/>
</SecretKey>

提供用于验证或签署使用 HMAC 算法的令牌的密钥。仅在算法是 HS256/HS384/HS512 之一时使用。使用 ref 属性在流变量中传递密钥。

Edge 为 HS256/HS384/HS512 算法强制执行最小密钥强度。HS256 的最小密钥长度为 32 个字节,HS384 为 48 个字节,而 HS512 则为 64 个字节。使用较低强度的密钥会导致运行时错误。

默认 不适用
状态 HMAC 算法所需的属性。
类型 字符串
有效值 引用字符串的流变量

注意:如果使用流变量,则其前缀必须为“private”。例如:private.mysecret

<Subject>

<Subject>subject-string-here</Subject>
或
<Subject ref="flow_variable" />

例如:

<Subject ref="apigee.developer.email"/>

该政策会生成一个 JWT,其中包含设置为指定值的 sub 声明。此声明可以标识或发出关于 JWT 主题的声明。这是 RFC7519 中所述的标准声明组之一。

默认 不适用
状态 可选
类型 字符串
有效值 唯一标识主题的任何值或引用值的流变量。

流变量

生成 JWT 政策不设置流变量。

错误参考信息

This section describes the fault codes and error messages that are returned and fault variables that are set by Edge when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Occurs when
steps.jwt.AlgorithmInTokenNotPresentInConfiguration 401 Occurs when the verification policy has multiple algorithms.
steps.jwt.AlgorithmMismatch 401 The algorithm specified in the Generate policy did not match the one expected in the Verify policy. The algorithms specified must match.
steps.jwt.FailedToDecode 401 The policy was unable to decode the JWT. The JWT is possibly corrupted.
steps.jwt.GenerationFailed 401 The policy was unable to generate the JWT.
steps.jwt.InsufficientKeyLength 401 For a key less than 32 bytes for the HS256 algorithm, less than 48 bytes for the HS386 algortithm, and less than 64 bytes for the HS512 algorithm.
steps.jwt.InvalidClaim 401 For a missing claim or claim mismatch, or a missing header or header mismatch.
steps.jwt.InvalidCurve 401 The curve specified by the key is not valid for the Elliptic Curve algorithm.
steps.jwt.InvalidJsonFormat 401 Invalid JSON found in the header or payload.
steps.jwt.InvalidToken 401 This error occurs when the JWT signature verification fails.
steps.jwt.JwtAudienceMismatch 401 The audience claim failed on token verification.
steps.jwt.JwtIssuerMismatch 401 The issuer claim failed on token verification.
steps.jwt.JwtSubjectMismatch 401 The subject claim failed on token verification.
steps.jwt.KeyIdMissing 401 The Verify policy uses a JWKS as a source for public keys, but the signed JWT does not include a kid property in the header.
steps.jwt.KeyParsingFailed 401 The public key could not be parsed from the given key information.
steps.jwt.NoAlgorithmFoundInHeader 401 Occurs when the JWT contains no algorithm header.
steps.jwt.NoMatchingPublicKey 401 The Verify policy uses a JWKS as a source for public keys, but the kid in the signed JWT is not listed in the JWKS.
steps.jwt.SigningFailed 401 In GenerateJWT, for a key less than the minimum size for the HS384 or HS512 algorithms
steps.jwt.TokenExpired 401 The policy attempts to verify an expired token.
steps.jwt.TokenNotYetValid 401 The token is not yet valid.
steps.jwt.UnhandledCriticalHeader 401 A header found by the Verify JWT policy in the crit header is not listed in KnownHeaders.
steps.jwt.UnknownException 401 An unknown exception occurred.
steps.jwt.WrongKeyType 401 Wrong type of key specified. For example, if you specify an RSA key for an Elliptic Curve algorithm, or a curve key for an RSA algorithm.

Deployment errors

These errors can occur when you deploy a proxy containing this policy.

Error name Cause Fix
InvalidNameForAdditionalClaim The deployment will fail if the claim used in the child element <Claim> of the <AdditionalClaims> element is one of the following registered names: kid, iss, sub, aud, iat, exp, nbf, or jti.
InvalidTypeForAdditionalClaim If the claim used in the child element <Claim> of the <AdditionalClaims> element is not of type string, number, boolean, or map, the deployment will fail.
MissingNameForAdditionalClaim If the name of the claim is not specified in the child element <Claim> of the <AdditionalClaims> element, the deployment will fail.
InvalidNameForAdditionalHeader This error ccurs when the name of the claim used in the child element <Claim> of the <AdditionalClaims> element is either alg or typ.
InvalidTypeForAdditionalHeader If the type of claim used in the child element <Claim> of the <AdditionalClaims> element is not of type string, number, boolean, or map, the deployment will fail.
InvalidValueOfArrayAttribute This error occurs when the value of the array attribute in the child element <Claim> of the <AdditionalClaims> element is not set to true or false.
InvalidConfigurationForActionAndAlgorithm If the <PrivateKey> element is used with HS Family algorithms or the <SecretKey> element is used with RSA Family algorithms, the deployment will fail.
InvalidValueForElement If the value specified in the <Algorithm> element is not a supported value, the deployment will fail.
MissingConfigurationElement This error will occur if the <PrivateKey> element is not used with RSA family algorithms or the <SecretKey> element is not used with HS Family algorithms.
InvalidKeyConfiguration If the child element <Value> is not defined in the <PrivateKey> or <SecretKey> elements, the deployment will fail.
EmptyElementForKeyConfiguration If the ref attribute of the child element <Value> of the <PrivateKey> or <SecretKey> elements is empty or unspecified, the deployment will fail.
InvalidVariableNameForSecret This error occurs if the flow variable name specified in the ref attribute of the child element <Value> of the <PrivateKey> or <SecretKey> elements does not contain the private prefix (private.).
InvalidSecretInConfig This error occurs if the child element <Value> of the <PrivateKey> or <SecretKey> elements does not contain the private prefix (private.).
InvalidTimeFormat If the value specified in the<NotBefore> element does not use a supported format, the deployment will fail.

故障变量

发生运行时错误时,系统会设置这些变量。如需了解详情,请参阅您需要了解的有关政策错误的信息。

变量 地点 示例
fault.name="fault_name" fault_name 是故障名称,如上面的运行时错误表中所列。故障名称是故障代码的最后一部分。 fault.name Matches "TokenExpired"
JWT.failed 所有 JWT 政策都将在发生故障时设置同一变量。 JWT.failed = true

错误响应示例

JWT 政策故障代码

处理错误时,最佳做法是捕获错误响应的 errorcode 部分。不要依赖 faultstring 中的文本,因为它可能会发生变化。

故障规则示例

    <FaultRules>
        <FaultRule name="JWT Policy Errors">
            <Step>
                <Name>JavaScript-1</Name>
                <Condition>(fault.name Matches "TokenExpired")</Condition>
            </Step>
            <Condition>JWT.failed=true</Condition>
        </FaultRule>
    </FaultRules>