GenerateJWT policy

This page applies to Apigee and Apigee hybrid.

View Apigee Edge documentation.

policy icon

What

Generates a signed JWT or an encrypted JWT, with a configurable set of claims. The JWT can then be returned to clients, transmitted to backend targets, or used in other ways. See JWS and JWT policies overview for a detailed introduction.

This policy is an Extensible policy and use of this policy might have cost or utilization implications, depending on your Apigee license. For information on policy types and usage implications, see Policy types.

How

Whether the policy generates a signed or encrypted JWT depends on the element you use to specify the algorithm that generates the JWT:

Video

Watch a short video to learn how to generate a signed JWT.

Generate a Signed JWT

This section explains how to generate a signed JWT. For a signed JWT, use the <Algorithm> element to specify the algorithm for signing the key.

Samples for a signed JWT

The following samples illustrate how to generate a signed JWT.

HS256 algorithm

This example policy generates a new JWT and signs it using the HS256 algorithm. HS256 relies on a shared secret for both signing and verifying the signature.

When this policy action is triggered, Apigee encodes the JWT header and payload, then digitally signs the JWT. See the video above for a complete example, including how to make a request to the policy.

The policy configuration here will create a JWT with a set of standard claims as defined by the JWT specification, including an expiry of 1 hour, as well as an additional claim. You can include as many additional claims as you wish. See the Element reference for details on the requirements and options for each element in this sample policy.

<GenerateJWT name="JWT-Generate-HS256">
    <DisplayName>JWT Generate HS256</DisplayName>
    <Type>Signed</Type>
    <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-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>

The resulting JWT will have this header …

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

… and will have a payload with contents something like this:

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

The value of the iat, exp, and jti claims will vary.

RS256 algorithm

This example policy generates a new JWT and signs it using the RS256 algorithm. Generating an RS256 signature relies on an RSA private key, which must be provided in PEM-encoded form, and which may be password-encrypted. See the video above for a complete example, including how to make a request to the policy.

When this policy action is triggered, Apigee encodes and digitally signs the JWT, including the claims. To learn about the parts of a JWT and how they are encrypted and signed, refer to RFC7519.

<GenerateJWT name="JWT-Generate-RS256">
    <Type>Signed</Type>
    <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-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>

The samples above use the <Algorithm> element, so they generate a signed JWT. The <PrivateKey> element specifies the cryptographic key used to sign the JWT. There are other key elements as well. Which one you use depends on the algorithm specified by the value of <Algorithm>, as described in the next section.

Setting the key elements for a signed JWT

Use exactly one of the following elements to specify the key used to generate a signed JWT:

Which element you use depends on the chosen algorithm, as shown in the following table:

Algorithm Key elements
HS{256/384/512}*
<SecretKey>
  <Value ref="private.secretkey"/>
  <Id ref="secretkey-id">key-1918290</Id>
</SecretKey>
RS/PS/ES{256/384/512}*
<PrivateKey>
  <Value ref="private.privatekey"/>
  <Password ref="private.privatekey-password"/>
  <Id ref="privatekey-id">key-1918290</Id>
</PrivateKey>

In the examples above, the <Password> and <Id> elements are optional.

For more on the key requirements, see About signature encryption algorithms.

Generate an encrypted JWT

This section explains how to generate an encrypted JWT. For an encrypted JWT, use the <Algorithms> element to specify the algorithms for signing the key and content.

Sample for an encrypted JWT

The following sample shows how to generate an encrypted JWT. The sample uses the <Algorithms> element, so it generates an encrypted JWT.

RSA-OAEP-256

In the example below:

  • The key is encrypted with the RSA-OAEP-256 algorithm.
  • The content is encrypted with the A128GCM algorithm.

The <PublicKey> element specifies the key used for key encryption.

<GenerateJWT name="gjwt-1">
  <Type>Encrypted</Type>
  <Algorithms>
    <Key>RSA-OAEP-256</Key>
    <Content>A128GCM</Content>
  </Algorithms>
  <PublicKey>
    <Value ref="rsa_publickey"/>
  </PublicKey>
  <Subject>subject@example.com</Subject>
  <Issuer>urn://apigee</Issuer>
  <ExpiresIn>1h</ExpiresIn>
  <AdditionalHeaders>
    <Claim name="moniker">Harvey</Claim>
  </AdditionalHeaders>
  <OutputVariable>output_var</OutputVariable>
</GenerateJWT>

A128KW

In the example below:

  • The key is encrypted with the A128KW algorithm.
  • The content is encrypted with the A128GCM algorithm.

The <SecretKey> element specifies the key used for key encryption.

<GenerateJWT name='gjwt-2'>
  <Algorithms>
    <Key>A128KW</Key>
    <Content>A128GCM</Content>
  </Algorithms>
  <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
  <SecretKey>
    <Value ref='private.secretkey'/>
  </SecretKey>
  <Subject>subject@example.com</Subject>
  <Issuer>urn://apigee</Issuer>
  <ExpiresIn>1h</ExpiresIn>
  <OutputVariable>output_var</OutputVariable>
</GenerateJWT>

Setting the key elements for an encrypted JWT

Use exactly one of the following elements to specify the encryption key for GenerateJWT, when you want to generate an encrypted JWT:

Which element you use depends on the chosen key encyryption algorithm, as shown in the following table:

Key encryption algorithm Key elements
RSA-OAEP-256
<PublicKey>
  <Value ref="rsa_publickey"/>
</PublicKey>

Note: The key must resolve to an RSA public key.

  • ECDH-ES
  • ECDH-ES+A128KW
  • ECDH-ES+A192KW
  • ECDH-ES+A256KW
<PublicKey>
  <Value ref="ec_publickey"/>
</PublicKey>

Note: The key must resolve to an elliptic curve public key.

  • A128KW
  • A192KW
  • A256KW
  • A128GCMKW
  • A192GCMKW
  • A256GCMKW
<SecretKey>
  <Id>optional key identifier here</Id>
  <Value ref="private.secretkey"/>
</SecretKey>
  • PBES2-HS256+A128KW
  • PBES2-HS384+A192KW
  • PBES2-HS512+A256KW
<PasswordKey>
  <Id>optional key identifier here</Id>
  <Value ref="private.passwordkey"/>
  <SaltLength>
  <PBKDF2Iterations>
</PasswordKey>
dir
<DirectKey>
  <Id>optional key identifier here</Id>
  <Value encoding="base16|hex|base64|base64url" ref="private.directkey"/>
</DirectKey>

For more on the key requirements, see About signature encryption algorithms.

Element reference for Generate JWT

The policy reference describes the elements and attributes of the Generate JWT policy.

Note: Configuration will differ somewhat depending on the encryption algorithm you use. Refer to Samples for a signed JWT or Sample for an encrypted JWT for examples that demonstrate configurations for specific use cases.

Attributes that apply to the top-level element

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

The following attributes are common to all policy parent elements.

Attribute Description Default Presence
name The internal name of the policy. Characters you can use in the name are restricted to: A-Z0-9._\-$ %. However, the Apigee UI enforces additional restrictions, such as automatically removing characters that are not alphanumeric.

Optionally, use the <displayname></displayname> element to label the policy in the Apigee UI proxy editor with a different, natural-language name.

N/A Required
continueOnError Set to false to return an error when a policy fails. This is expected behavior for most policies.

Set to true to have flow execution continue even after a policy fails.

false Optional
enabled Set to true to enforce the policy.

Set to false to "turn off" the policy. The policy will not be enforced even if it remains attached to a flow.

true Optional
async This attribute is deprecated. false Deprecated

<DisplayName>

<DisplayName>Policy Display Name</DisplayName>

Use in addition to the name attribute to label the policy in the Apigee UI proxy editor with a different, natural-language name.

Default If you omit this element, the value of the policy's name attribute is used.
Presence Optional
Type String

<Algorithm>

<Algorithm>algorithm-here</Algorithm>

Specifies the cryptographic algorithm used to sign the token. Use the <Algorithm> element to generate a signed JWT.

Default N/A
Presence Optional. One of <Algorithm> or <Algorithms> is required.
Type String
Valid values HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512

<Algorithms>

<Algorithms>
    <Key>key-algorithm</Key>
    <Content>content-algorithm</Content>
</Algorithm>

Specifies the cryptographic algorithms for the key and content encryption. Use the <Algorithms> element to generate an encrypted JWT.

Default N/A
Optional. One of <Algorithm> or <Algorithms> is required. Required
Type String

Child elements of <Algorithms>

The following table provides a high-level description of the child elements of <Algorithms>:

Child Element Required? Description
<Key> Required Specifies the encryption algorithm for the key.
<Content> Required Specifies the encryption algorithm for the content.

Key encryption algorithms

The following table lists the available algorithms for key encryption.

Value of <Key> (key encryption algorithm) Key element required
dir <DirectKey>
RSA-OAEP-256 <PublicKey> (which must resolve to an RSA public key)
  • A128KW
  • A192KW
  • A256KW
  • A128GCMKW
  • A192GCMKW
  • A256GCMKW
<SecretKey>
  • PBES2-HS256+A128KW
  • PBES2-HS384+A192KW
  • PBES2-HS512+A256KW
<PasswordKey>
  • ECDH-ES
  • ECDH-ES+A128KW
  • ECDH-ES+A192KW
  • ECDH-ES+A256KW
<PublicKey> (which must resolve to an elliptic curve public key)

See Generate an encrypted JWT for an example in which the key encryption algorithm is RSA-OAEP-256, so you use the <PublicKey> element with value that resolves to an RSA Public key.

Content encryption algorithms

The following algorithms (symmetric, AES-based) are available for content encryption:

  • A128CBC-HS256
  • A192CBC-HS384
  • A256CBC-HS512
  • A128GCM
  • A192GCM
  • A256GCM

For more information on all of these algorithms, see RFC7518.

<Audience>

<Audience>audience-here</Audience>

or:

<Audience ref='variable_containing_audience'/>

The policy generates a JWT containing an aud claim set to the specified value. This claim identifies the recipients that the JWT is intended for. This is one of the registered claims mentioned in RFC7519.

Default N/A
Presence Optional
Type Array (a list of comma-separated values)
Valid values Anything that identifies the audience.

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

Lets you specify additional claim name/value pair(s) in the payload of the JWT. You can specify the claim explicitly as string, a number, a boolean, a map, or an array. A map is simply a set of name/value pairs.

Default N/A
Presence Optional
Valid values Any value that you want to use for an additional claim. You can specify the claim explicitly as string, a number, a boolean, a map, or an array.

The <Claim> element takes these attributes:

  • name - (Required) The name of the claim.
  • ref - (Optional) The name of a flow variable. If present, the policy will use the value of this variable as the claim. If both a ref attribute and an explicit claim value are specified, the explicit value is the default, and is used if the referenced flow variable is unresolved.
  • type - (Optional) One of: string (default), number, boolean, or map
  • array - (Optional) Set to true to indicate if the value is an array of types. Default: false.

When you include the <Claim> element, the claim names are set statically when you configure the policy. Alternatively, you can pass a JSON object to specify the claim names. Because the JSON object is passed as a variable, the claim names in the generated JWT are determined at runtime.

For example:

<AdditionalClaims ref='json_claims'/>

Where the variable json_claims contains a JSON object in the form:

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

The generated JWT includes all of the claims in the JSON object.

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

Puts the additional claim name/value pair(s) in the header for the JWT.

Default N/A
Presence Optional
Valid values Any value that you want to use for an additional claim. You can specify the claim explicitly as string, a number, a boolean, a map, or an array.

The <Claim> element takes these attributes:

  • name - (Required) The name of the claim.
  • ref - (Optional) The name of a flow variable. If present, the policy will use the value of this variable as the claim. If both a ref attribute and an explicit claim value are specified, the explicit value is the default, and is used if the referenced flow variable is unresolved.
  • type - (Optional) One of: string (default), number, boolean, or map
  • array - (Optional) Set to true to indicate if the value is an array of types. Default: false.

<Compress>

<Compress>true</Compress>

Specifies whether text is compressed before encrypting. This element is valid only when generating an encrypted JWT.

<CriticalHeaders>

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

or:

<CriticalHeaders ref=variable_containing_headers/>

Adds the critical header, crit, to the JWT header. The crit header is an array of header names that must be known and recognized by the JWT receiver. For example:

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

According to the specification, verifying parties must examine the crit header and verify that each of those headers is understood. For example, the VerifyJWT policy examines the crit header. For each item listed in the crit header, it checks that the <KnownHeaders> element of the VerifyJWT policy also lists that header. Any header that the VerifyJWT policy finds in crit that is not also listed in <KnownHeaders> causes the VerifyJWT policy to fail.

Default N/A
Presence Optional
Type Comma separated array of strings
Valid values Either an array or the name of a variable containing the array.

<CustomClaims>

Note: Currently, a CustomClaims element is inserted when you add a new GenerateJWT policy through the UI. This element is not functional and is ignored. The correct element to use instead is <AdditionalClaims>. The UI will be updated to insert the correct elements at a later time.

<DirectKey>

<DirectKey>
  <Id>A12345</Id>
  <Value encoding="base16|hex|base64|base64url" ref="private.directkey"/>
</DirectKey>

Specifies a direct key for encrypting a JWT when the encryption algorithm is dir ("direct encryption").

Child elements of <DirectKey>

The following table provides a high-level description of the child elements of <DirectKey>:

Child Element Required? Description
Id Optional Key identifier
Value Required Specify a reference to a variable with the ref attribute. The contents of the referenced variable must be a string encoding of a byte array, encoded via one of hex (base16), base64, or base64url.

With direct key encryption, you can directly supply a series of bytes that will act as the content encryption key (CEK). You must specify the byte array as an encoded string. The required length of the byte array depends on the strength of the content encryption algorithm selected. For example, for A256CBC-HS512, you must supply a key of exactly 512 bits, or 64 bytes.

The contents of the variable private.directkey must be a string that is encoded, either via hex (base16), base64, or base64url. For example, here is a hex-encoded 32-byte key:

96 4b e1 71 15 71 5f 87 11 0e 13 52 4c ec 1e ba df 47 62 1a 9d 3b f5 ad d2 7b b2 35 e7 d6 17 11

For the hex encoding, whitespace is accepted but not required, and upper or lowercase is accepted (B7 is the same as b7).

The base64url-encoded equivalent of the above is:

lkvhcRVxX4cRDhNSTOweut9HYhqdO/Wt0nuyNefWFxE

For the base64* variants, whitespace is not accepted, and case matters. If you don't specify an encoding, the policy assumes the encoding is base64.

The following describes the length of keys required:

Content Encryption Algorithm Key length requirement
A128CBC-HS256 256 bits (32 bytes)
A192CBC-HS384 384 (48)
A256CBC-HS512 512 (64)
A128GCM 128 (16)
A192GCM 192 (24)
A256GCM 256 (32)

Note: The content-encryption key provided via the <DirectKey> element must be exactly the right length for the specified content-encryption algorithm. For any key-encryption algorithm other than dir, the policy generates a random CEK that is the right length, but for dir, the configuration needs to supply a key with the right size explicitly.

<ExpiresIn>

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

or:

<ExpiresIn ref='time-value-here'/>

Specifies the lifespan of the JWT in milliseconds, seconds, minutes, hours, or days. Specify the expiration using either the XML element or the ref attribute, but not both.

Default N/A
Presence Optional
Type Integer
Valid values

A value or a reference to a flow variable containing the value. Time units can be specified as follows:

  • ms = milliseconds (default)
  • s = seconds
  • m = minutes
  • h = hours
  • d = days

For example, an ExpiresIn=10d is equivalent to an ExpiresIn of 864000s.

<Id>

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

Generates a JWT with the specific jti claim. When the text value and ref attribute are both empty, the policy will generate a jti containing a random UUID. The JWT ID (jti) claim is a unique identifier for the JWT. For more information on jti, refer to RFC7519.

Default N/A
Presence Optional
Type String, or reference.
Valid values Either a string or the name of a flow variable containing the ID.

<IgnoreUnresolvedVariables>

<IgnoreUnresolvedVariables>true|false</IgnoreUnresolvedVariables>

Set to false if you want the policy to throw an error when any referenced variable specified in the policy is unresolvable. Set to true to treat any unresolvable variable as an empty string (null).

Default False
Presence Optional
Type Boolean
Valid values true or false

<Issuer>

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

The policy generates a JWT containing a claim with name iss, with a value set to the specified value. A claim that identifies the issuer of the JWT. This is one of the registered set of claims mentioned in RFC7519.

Default N/A
Presence Optional
Type String, or reference
Valid values Any

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

Specifies the time when the token becomes valid. The token is invalid until the specified time. You can specify either an absolute time value, or a time relative to when the token is generated.

Default N/A
Presence Optional
Type String
Valid values See below.

Valid time values for the NotBefore element for absolute time values

Name Format Example
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

For relative time values, specify an integer and a time period, for example:

  • 10s
  • 60m
  • 12h

<OutputVariable>

<OutputVariable>jwt-variable</OutputVariable>

Specifies where to place the JWT generated by this policy. By default it is placed into the flow variable jwt.POLICYNAME.generated_jwt.

Default jwt.POLICYNAME.generated_jwt
Presence Optional
Type String (a flow variable name)

<PasswordKey>

<PasswordKey>
  <Id>abcdefg</Id>
  <Value ref="private.password"/>
  <SaltLength>8</SaltLength>
  <PBKDF2Iterations>10000</PBKDF2>
</PasswordKey>

Specifies a key for encrypting a JWT when the encryption algorithm is one of the following:

  • PBES2-HS256+A128KW
  • PBES2-HS384+A192KW
  • PBES2-HS512+A256KW

For each of these key algorithms, you must supply a password from which the key encryption key is derived, via the variable private.password in the element <Value ref="private.password"/>.

Child elements of <PasswordKey>

The following table provides a high-level description of the child elements of <PasswordKey>:

Child Element Presence Description
Id Optional Key identifier
Value Required Specifies the password used to generate the key encryption key. Use a ref attribute and specify a variable, such as private.password .
SaltLength Optional Salt length. Default: 8 bytes.
PBKDF2Iterations Optional PBKDF2 iteration count: Default: 10000.

<PrivateKey>

<PrivateKey>
  <Id ref="privatekey-id"/>
  <Value ref="private.pem-encoded-privatekey"/>
  <Password ref="private.privatekey-password"/>
</PrivateKey>

Specifies the private key to use when generating a signed JWT, and the Algorithm is an RSA or elliptic curve (EC) variant - one of RS256/RS384/RS512, PS256/PS384/PS512, or ES256/ES384/ES512.

Child elements of <PrivateKey>

The following table provides a description of the child elements of <PrivateKey>:

Child Element Presence Description
Id Optional

The key identifier. The value can be any string. You can specify the value as a literal text value, or indirectly, via a variable reference, with the ref attribute.

The policy will include this key identifier as the kid claim in the header of the generated JWT.

Value Required

A PEM-encoded private key. Specifies the private key used to sign the payload. Use a ref attribute and specify a variable, such as private.private-key .

If the <Algorithm> element holds an RSA variant, one of RS256/RS384/RS512 or PS256/PS384/PS512, then you must supply an encoded RSA private key. If the <Algorithm> element holds an EC variant, one of ES256/ES384/ES512, then you must supply a Elliptic Curve private key for the appropriate curve.

Password Optional

The password the policy should use to decrypt the private key, if necessary. Use the ref attribute to pass the password via a flow variable.

Note: You must specify a flow variable. Apigee will reject as invalid a policy configuration in which the password is specified in plaintext. The flow variable must have the prefix "private". For example, private.mypassword

<PublicKey>

<PublicKey>
  <!-- specify exactly one of the following -->
  <Value ref="variable-containing-encoded-publickey"/>
  <Value>PEM encoded public key</Value>
  <Certificate ref="variable-containing-encoded-x509-certificate"/>
  <Certificate>PEM encoded X509 certificate</Certificate>
  <JWKS>jwks-content</JWKS>
  <JWKS ref="variable-containing-jwks-content"/>
  <JWKS uri="variable-containing-jwks-content"/>
  <JWKS uriRef="variable-containing-uri"/>
</PublicKey>

Specifies the public key to use when generating an encrypted JWT, and the Key algorithm is an RSA or elliptic curve (EC) variant - RSA-OAEP-256, ECDH-ES, ECDH-ES+A128KW, ECDH-ES+A192KW, or ECDH-ES+A256KW.

Child elements of <PublicKey>

Provide exactly one of Value, Certificate, or JWKS. If you specify JWKS, you must also specify Id. The following table provides a description of these child elements of <PublicKey>:

Child Element Description
Value

A PEM-encoded public key. Specifies the public key that the policy should use to encrypt the content-encryption key. You may specify the key literally, or indirectly via a variable reference.

<PublicKey>
  <Value ref="public.publickey"/>
</PublicKey>

or

<PublicKey>
  <Value>
   -----BEGIN PUBLIC KEY-----
   MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw2kPrRzcufvUNHvTH/WW
   2F73IyN....your key will vary....1jC0dwUD1lHV8MfUyRXmpmnNxJHACof
   C5TBtXMORc+us7A2cTtC4gZV256bT4h3sIEMsDl0Joz9K9MPzVPFxa1i0RgNt06n
   ZmkDb/DRW5onclGzxQITBFP3S6JXd4LNESJcTp705ec1cQ9Wp2Kl+nKrKyv1E5Xx
   DQIDAQAB
   -----END PUBLIC KEY-----
  </Value>
</PublicKey>

The encoded public key must denote an RSA key if you use the RSA-OAEP-256 algorithm, or an EC key of the appropriate curve if you use an EC algorithm.

Certificate

A PEM-encoded X.509 certificate, wrapping a public key. Apigee will extract the public key from the certificate, and then use that key to encrypt the content-encryption key. You may specify the certificate literally, or indirectly via a variable reference.

<PublicKey>
 <Certificate ref="public.pem-encoded-certificate"/>
</PublicKey>

or

<PublicKey>
  <Certificate>
  -----BEGIN CERTIFICATE-----
  MIIDqDCCApACCQCG/xVb7Yzw3zANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMC
  2F73IyN....your certificate data will vary....1jC0dwUD1lHV8MfUyR
  VQQKDAZHb29nbGUxDzANBgNVBAsMBkFwaWdlZTEaMBgGA1UEAwwRYXBpZ2VlLmdv
  ...
  YjBaZuNUDVLGvbTSRgWG5lwm85Jar2zeCBcxFDwqyZFvVNV9SfoWF/LgVVpK54n8
  rknZ17USb0ob51ckxPTENmF2DUHBzgptiw10Yw==
  -----END CERTIFICATE-----
  </Certificate>
</PublicKey>

The encoded public key must denote an RSA key if you use the RSA-OAEP-256 algorithm, or an EC key of the appropriate curve if you use an EC algorithm.

JWKS

A JWKS source of public keys. This will be a list of keys following the format described in IETF RFC 7517 - JSON Web Key (JWK).

You can specify the JWKS in one of four ways:

  • literally, as a text value:

    <PublicKey>
      <JWKS>jwks-content-here</JWKS>
      <Id ref="variable-containing-a-kid">literal-value-here</Id>
    </PublicKey>
  • indirectly, with the ref attribute, specifying a flow variable:

    <PublicKey>
      <JWKS ref="variable-containing-jwks-content"/>
      <Id ref="variable-containing-a-kid">literal-value-here</Id>
    </PublicKey>

    The referenced variable should contain a string that represents a JWKS.

  • indirectly via a static uri, with the uri attribute:

    <PublicKey>
      <JWKS uri="uri-that-returns-a-jwks"/>
      <Id ref="variable-containing-a-kid">literal-value-here</Id>
    </PublicKey>
  • indirectly via a dynamically-determined uri, with the uriRef attribute:

    <PublicKey>
      <JWKS uriRef="variable-containing-a-uri-that-returns-a-jwks"/>
      <Id ref="variable-containing-a-kid">literal-value-here</Id>
    </PublicKey>

In all cases, when specifying a JWKS element within GenerateJWT to generate an encrypted JWT, you must also specify the PublicKey/Id element.

<PublicKey>
  <JWKS uri="uri-that-returns-a-jwks"/>
  <Id ref="variable-containing-a-kid">literal-value-here</Id>
</PublicKey>
Id

A string representing the key identifier. At runtime, Apigee retrieves a key from the JWKS that has a kid field that matches this value. The Id element is required if you use the JWKS element within GenerateJWT.

<SecretKey>

<SecretKey encoding="base16|hex|base64|base64url" >
 <Id ref="variable-containing-key-id-here">secret-key-id</Id>
 <Value ref="private.variable-here"/>
</SecretKey>

The SecretKey element is optional. It specifies the secret key to use when generating a signed JWT that uses a symmetric (HS*) algorithm or when generating an encrypted JWT that uses a symmetric (AES) algorithm for key encryption.

Children of <SecretKey>

The following table provides a description of the child elements and attributes of <SecretKey>:

Child Presence Description
encoding (attribute) Optional

Specifies how the key is encoded in the referenced variable. By default, when no encoding attribute is present, the encoding of the key is treated as UTF-8. Valid values for the attribute are: hex, base16, base64, or base64url. The encoding values hex and base16 are synonyms.

<SecretKey encoding="VALUE_HERE" >
 <Id ref="variable-containing-key-id-here">secret-key-id</Id>
 <Value ref="private.secretkey"/>
</SecretKey>

In the above example, when the encoding attribute is hex, and the contents of the variable private.secretkey is 494c6f766541504973, the key will be decoded as a set of 9 bytes, which in hex will be 49 4c 6f 76 65 41 50 49 73. Conversely, when the encoding attribute is base64, and the contents of the variable private.secretkey is VGhpcy1pcy1hLXNlY3JldA, the key will be decoded as a set of 16 bytes, in hex: 54 68 69 73 2d 69 73 2d 61 2d 73 65 63 72 65 74.

Id (element) Optional

The key identifier. The value can be any string. You can specify the value as a literal text value, or indirectly, via a variable reference, with the ref attribute.

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

or

<SecretKey>
  <Id>your-id-value-here</Id>
 <Value ref="private.variable-here"/>
</SecretKey>

The policy will include this key identifier as the kid claim in the header of the generated JWT.

Value (element) Required

An encoded secret key. Specifies the secret key used to sign the payload. Use the ref attribute to provide the key indirectly via a variable, such as private.secret-key .

<SecretKey>
 <Id ref="flow-variable-name-here"/>
  <Value ref="private.my-secret-variable"/>
</SecretKey>

Apigee enforces a minimum key strength for the HS256/HS384/HS512 algorithms. The minimum key length for HS256 is 32 bytes, for HS384 it is 48 bytes, and for HS512 it is 64 bytes. Using a lower-strength key causes a runtime error.

<Subject>

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

For example:

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

The policy generates a JWT containing a sub claim, set to the specified value.This claim identifies or makes a statement about the subject of the JWT. This is one of the standard set of claims mentioned in IETF RFC 7519.

Default N/A
Presence Optional
Type String
Valid values Any value uniquely identifying a subject or a flow variable referring to a value.

<Type>

<Type>type-string-here</Type>

Describes whether the policy generates a signed JWT or an encrypted JWT. The <Type> element is optional. You can use it to inform readers of the configuration whether the policy generates a signed or an encrypted JWT.

  • If the <Type> element is present:
    • If the value of <Type> is Signed, the policy generates a signed JWT, and the <Algorithm> element must be present.
    • If the value of <Type> is Encrypted, the policy will generate an encrypted JWT, and the <Algorithms> element must be present.
  • If the <Type> element is absent:
    • If the <Algorithm> element is present, the policy assumes <Type> is Signed.
    • If the <Algorithms> element is present, the policy assumes <Type> is Encrypted.
  • If neither <Algorithm> nor <Algorithms> is present, the configuration is invalid.
Default N/A
Presence Optional
Type String
Valid values Either Signed or Encrypted

Flow variables

The Generate JWT policy does not set flow variables.

Error reference

This section describes the fault codes and error messages that are returned and fault variables that are set by Apigee 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.EncryptionFailed 401 Creation of an encrypted JWT failed for a non-specific reason
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.InvalidConfiguration 401 Both the <Algorithm> and <Algorithms> elements are present.
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.InvalidPasswordKey 401 The specified key specified did not meet the requirements.
steps.jwt.InvalidPrivateKey 401 The specified key specified did not meet the requirements.
steps.jwt.InvalidPublicKey 401 The specified key specified did not meet the requirements.
steps.jwt.InvalidSecretKey 401 The specified key specified did not meet the requirements.
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 "InvalidToken"
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 "InvalidToken")</Condition>
            </Step>
            <Condition>JWT.failed=true</Condition>
        </FaultRule>
    </FaultRules>