GenerateJWT ポリシー

概要

構成可能な一連のクレームを含む、署名付きの JWT を生成します。JWT はクライアントに返すことができます。また、バックエンド ターゲットに送信するなど、他の方法で使用することもできます。詳細については、JWS ポリシーと JWT ポリシーの概要をご覧ください。

動画

署名付きの JWT を生成する方法について、短い動画をご覧ください。

サンプル

HS256 アルゴリズムで署名された JWT を生成する

このポリシー サンプルでは、新しい JWT を生成し、HS256 アルゴリズムを使用して署名します。HS256 は、署名とその検証の両方に共有シークレットを利用します。

このポリシー アクションがトリガーされると、Edge は JWT ヘッダーとペイロードをエンコードし、JWT にデジタル署名します。ポリシーに対してリクエストする方法など、詳しい例については上記の動画をご覧ください。

このサンプルのポリシー構成は、JWT 仕様で定義されている一連の標準的なクレーム(これには有効期間 1 時間のクレームも含まれます)と、追加クレーム 1 つからなる JWT を作成します。追加クレームは必要なだけ含めることができます。このサンプル ポリシーの各要素に関する要件とオプションの詳細については、要素リファレンスをご覧ください。

<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."
}

iatexpjti の各クレームの値は生成されるたびに変わります。

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> 要素は省略可能です。

* 鍵の要件の詳細については、署名暗号アルゴリズムについてをご覧ください。

Generate JWT の要素リファレンス

このポリシー リファレンスでは、Generate JWT ポリシーの要素と属性について説明しています。

注: 構成は使用する暗号化アルゴリズムにより異なります。特定のユースケースの構成例については、サンプルをご覧ください。

最上位の要素に適用される属性

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

次の属性は、すべてのポリシーの親要素に共通です。

属性 説明 デフォルト 要否
name ポリシーの内部名。名前に使用できる文字は A-Z0-9._\-$ % のみです。ただし、Edge 管理 UI では、英数字以外の文字を自動的に削除するなど、追加の制限が適用されます。

必要に応じて、<displayname></displayname> 要素を使用して、管理 UI プロキシ エディタでポリシーに別の自然言語名でラベルを付けます。

なし 必須
continueOnError ポリシーが失敗した場合にエラーを返すには、false に設定します。これはほとんどのポリシーで想定される動作です。

ポリシーが失敗してもフロー実行を続行するには、true に設定します。

false 省略可
enabled ポリシーを適用するには true に設定します。

ポリシーを「turn off」するには、false に設定します。ポリシーがフローに添付されている場合でも強制されません。

true 省略可
async この属性は非推奨となりました。 false 非推奨

<DisplayName>

<DisplayName>Policy Display Name</DisplayName>

name 属性に加えて、管理 UI プロキシ エディタのポリシーに別の自然言語名でラベルを付けるために使います。

デフォルト この要素を省略した場合、ポリシーの name 属性の値が使用されます。
要否 省略可
文字列

<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'/>

ポリシーは、指定された値に設定された aud クレームを含む JWT を生成します。このクレームは、この JWT を受け取ると想定された対象を識別します。これは、RFC7519 に記載されている登録済みクレームの 1 つです。

デフォルト なし
要否 省略可
配列(カンマ区切りの値のリスト)
有効な値 対象を識別する任意の値

<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> 要素には次の属性があります。

  • name -(必須)クレームの名前。
  • ref -(省略可)フロー変数の名前。設定された場合、ポリシーはこの変数の値をクレームとして使用します。ref 属性と明示的なクレーム値が両方指定された場合、明示的な値がデフォルトとなり、参照されたフロー変数が解決されない場合に使用されます。
  • type -(省略可)文字列(デフォルト)、数値、ブール値、マッピングのいずれか
  • array -(省略可)値が型の配列かどうかを示すには 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> 要素には次の属性があります。

  • name -(必須)クレームの名前。
  • ref -(省略可)フロー変数の名前。設定された場合、ポリシーはこの変数の値をクレームとして使用します。ref 属性と明示的なクレーム値が両方指定された場合、明示的な値がデフォルトとなり、参照されたフロー変数が解決されない場合に使用されます。
  • type -(省略可)文字列(デフォルト)、数値、ブール値、マッピングのいずれか
  • array -(省略可)値が型の配列かどうかを示すには true に設定します(デフォルトは false)。

<CriticalHeaders>

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

or:

<CriticalHeaders ref=’variable_containing_headers’/>

JWT ヘッダーに重大ヘッダーである crit を追加します。crit ヘッダーはヘッダー名の配列となり、JWT 受信者から既知で、認識される必要があります。例:

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

実行時に、VerifyJWT ポリシーcrit ヘッダーを確認します。crit ヘッダーにリストされたヘッダーごとに、VerifyJWT ポリシーの <KnownHeaders> 要素もそのヘッダーにリストされていることが確認されます。ポリシーが crit で検出したヘッダーの中に <KnownHeaders> にリストされていないものがあると、VerifyJWT ポリシーは失敗します。

デフォルト なし
要否 省略可
文字列のカンマ区切り配列
有効な値 配列または配列を含む変数の名前。

<CustomClaims>

注: 現在、UI を使用して新しい GenerateJWT ポリシーを追加すると CustomClaims 要素が挿入されます。この要素は機能していないため無視されます。代わりに使用する要素は <AdditionalClaims> です。あとで正しい要素が挿入されるように UI が更新されます。

<ExpiresIn>

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

JWT の寿命を、ミリ秒、秒、分、時、日で指定します。

デフォルト N/A
要否 省略可
Integer
有効な値

値、または値を含むフロー変数への参照。時間単位は、次のように指定できます。

  • ms = ミリ秒(デフォルト)
  • s = 秒
  • m = 分
  • h = 時
  • d = 日

たとえば、ExpiresIn = 10d は ExpiresIn が 864000s の場合と同等です。

<Id>

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

特定の jti クレームを持つ JWT を生成します。text 値と ref 属性が両方とも空白の場合、ポリシーはランダムな UUID を含む jti を生成します。JWT ID(jti)クレームは、JWT の一意の識別子です。jti の詳細については、RFC7519 をご覧ください。

デフォルト なし
要否 省略可
文字列または参照
有効な値 文字列または ID を含むフロー変数の名前

<IgnoreUnresolvedVariables>

<IgnoreUnresolvedVariables>true|false</IgnoreUnresolvedVariables>

false に設定すると、ポリシーで指定された参照値が解決できない場合にエラーを返します。true に設定すると、解決できない変数を空の文字列(null)として扱います。

デフォルト false
要否 省略可
Boolean
有効な値 true または false

<Issuer>

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

ポリシーは、iss というクレームを含む JWT を生成します。この値は指定した値に設定されます。JWT の発行者を識別するクレームで、RFC7519 に記載されている登録済みクレームの 1 つです。

デフォルト なし
要否 省略可
文字列または参照
有効な値 任意

<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 要素で有効な時間値

名前 形式
sortable 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 Mon, 14 Aug 2017 11:00:21 PDT
RFC 850 EEEE, dd-MMM-yy HH:mm:ss zzz Monday, 14-Aug-17 11:00:21 PDT
ANCI-C EEE MMM d HH:mm:ss yyyy Mon Aug 14 11:00:21 2017

相対時間値の場合は、整数と期間を指定します。次に例を示します。

  • 10s
  • 60m
  • 12h

<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(子)を指定します。アルゴリズムが 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 を生成するには必須。
文字列
有効な値 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(子)を指定します。アルゴリズムが HS256、HS384、HS512 のいずれかの場合にのみ使用します。

デフォルト なし
要否 省略可
文字列
有効な値 フロー変数または文字列

<SecretKey/Value>

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

HMAC アルゴリズムでトークンを検証するかトークンに署名するための秘密鍵です。アルゴリズムが HS256、HS384、HS512 のいずれかの場合にのみ使用します。ref 属性を使用して、鍵をフロー変数に渡します。

HS256 / HS384 / HS512 アルゴリズムの場合は、Edge による鍵の最小長の制限があります。鍵の最小長は、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"/>

ポリシーは、指定された値に設定された sub クレームを含む JWT を生成します。これは、RFC7519 に記載されている標準的なクレームの 1 つです。

デフォルト なし
要否 省略可
文字列
有効な値 主体を一意に識別する任意の値または値を参照するフロー変数。

フロー変数

Generate 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 variables

These variables are set when a runtime error occurs. For more information, see What you need to know about policy errors.

Variables Where Example
fault.name="fault_name" fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name Matches "TokenExpired"
JWT.failed All JWT policies set the same variable in the case of a failure. JWT.failed = true

Example error response

JWT Policy Fault Codes

For error handling, the best practice is to trap the errorcode part of the error response. Do not rely on the text in the faultstring, because it could change.

Example fault rule

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