VerifyJWT policy

This pageapplies toApigee andApigee hybrid.

View Apigee Edge documentation.

The VerifyJWT policy verifies a signed JWT or decrypts and verifies an encrypted JWT received from clients or other systems. This policy also extracts the claims into context variables so that subsequent policies or conditions can examine those values to make authorization or routing decisions. SeeJWS and JWT policies overview for a detailed introduction.

When this policy executes, in the case of a signed JWT, Apigee verifies the signature of the JWT using the provided verification key. In the case of an encrypted JWT, Apigee decrypts the JWT using the decryption key. In either case, Apigee subsequently verifies that the JWT is valid according to the expiry and not-before times if they are present. The policy can optionally also verify the values of specific claims on the JWT, such as the subject, the issuer, the audience, or the value of additional claims.

Note: If the policy configuration provides a certificate as the source of the public key, the runtime does not check the trust chain of the certificate and does not check the expiry of the certificate. The public key contained within the certificate is treated as valid and trusted.

If the JWT is verified and valid, then all of the claims contained within the JWT are extracted into context variables for use by subsequent policies or conditions, and the request is allowed to proceed. If the JWT signature cannot be verified or if the JWT is invalid because of one of the timestamps, all processing stops and an error is returned in the response.

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

This policy is aStandard policy and can be deployed to any environment type. For information on policy types and availability with each environment type, seePolicy types.

To learn about the parts of a JWT and how they are encrypted and signed, refer toRFC7519.

Verify a Signed JWT

This section explains how to verify 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 verify a signed JWT.

HS256 algorithm

This example policy verifies a JWT that was signed with the HS256 encryption algorithm, HMAC using a SHA-256 checksum. The JWT is passed in the proxy request by using a form parameter namedjwt. The key is contained in a variable namedprivate.secretkey. See the video above for a complete example, including how to make a request to the policy.

The policy configuration includes the information Apigee needs to decode and evaluate the JWT, such as where to find the JWT (in a flow variable specified in the Source element), the required signing algorithm, where to find the secret key (stored in an Apigee flow variable, which could have been retrieved from the Apigee KVM, for example), and a set of required claims and their values.

<VerifyJWT name="JWT-Verify-HS256">    <DisplayName>JWT Verify HS256</DisplayName>    <Algorithm>HS256</Algorithm>    <Source>request.formparam.jwt</Source>    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>    <SecretKey encoding="base64">        <Value ref="private.secretkey"/>    </SecretKey>    <Subject>monty-pythons-flying-circus</Subject>    <Issuer>urn://apigee-edge-JWT-policy-test</Issuer>    <Audience>fans</Audience>    <AdditionalClaims>        <Claim name="show">And now for something completely different.</Claim>    </AdditionalClaims></VerifyJWT>

The policy writes its output to context variables so that subsequent policies or conditions in the API proxy can examine those values. SeeFlow variables for a list of the variables set by this policy.

RS256 algorithm

Note:Use this same example to verify a JWT for the PS256 or ES256 algorithm. Just change the value of<Algorithm>RS256</Algorithm> toPS256 orES256. ForES256 you also have to specify the a key compatible with the algorithm. For more on the key requirements, seeAbout signature encryption algorithms.

This example policy verifies a JWT that was signed with the RS256 algorithm. To verify, you need to provide the public key. The JWT is passed in the proxy request by using a form parameter namedjwt. The public key is contained in a variable namedpublic.publickey. See the video above for a complete example, including how to make a request to the policy.

See the Element reference for details on the requirements and options for each element in this sample policy.

<VerifyJWT name="JWT-Verify-RS256">    <Algorithm>RS256</Algorithm>    <Source>request.formparam.jwt</Source>    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>    <PublicKey>        <Value ref="public.publickey"/>    </PublicKey>    <Subject>apigee-seattle-hatrack-montage</Subject>    <Issuer>urn://apigee-edge-JWT-policy-test</Issuer>    <Audience>urn://c60511c0-12a2-473c-80fd-42528eb65a6a</Audience>    <AdditionalClaims>        <Claim name="show">And now for something completely different.</Claim>    </AdditionalClaims></VerifyJWT>

For the above configuration, a JWT with this header …

{  "typ" : "JWT",  "alg" : "RS256"}

And this payload …

{  "sub" : "apigee-seattle-hatrack-montage",  "iss" : "urn://apigee-edge-JWT-policy-test",  "aud" : "urn://c60511c0-12a2-473c-80fd-42528eb65a6a",  "show": "And now for something completely different."}

… will be deemed as valid, if the signature can be verified with the provided public key.

A JWT with the same header but with this payload …

{  "sub" : "monty-pythons-flying-circus",  "iss" : "urn://apigee-edge-JWT-policy-test",  "aud" : "urn://c60511c0-12a2-473c-80fd-42528eb65a6a",  "show": "And now for something completely different."}

… will be determined to be invalid, even if the signature can be verified, because the "sub" claim included in the JWT does not match the required value of the "Subject" element as specified in the policy configuration.

The policy writes its output to context variables so that subsequent policies or conditions in the API proxy can examine those values. SeeFlow variables for a list of the variables set by this policy.

The samples above use the<Algorithm> element, so they verify a signedJWT. The<PrivateKey> element specifies the key used to sign the JWT. Thereare other key elements as well. Which one you use depends on the algorithm specified by thevalue of<Algorithm>, as described in the next section.

Setting the key elements to verify a signed JWT

The following elements specify the key used to verify a signed JWT:

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

Note:The RS*, PS*, and ES* algorithms all use the same elements to specify the key, but the ES* key data is different than that used by the RS* and PS* algorithms.
AlgorithmKey elements
HS*
<SecretKey encoding="base16|hex|base64|base64url">  <Value ref="private.secretkey"/></SecretKey>
RS*, ES*, PS*
<PublicKey>  <Value ref="rsa_public_key_or_value"/></PublicKey>

or:

<PublicKey>  <Certificate ref="signed_cert_val_ref"/></PublicKey>

or:

<PublicKey>  <JWKS ref="jwks_val_or_ref"/></PublicKey>
*For more on the key requirements, seeAbout signature encryption algorithms.

Verify an encrypted JWT

This section explains how to verify 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 verify an encrypted JWT (with<Type> set toEncrypted), in which:

  • The key is encrypted with the RSA-OAEP-256 algorithm.
  • The content is encrypted with the A128GCM algorithm.
<VerifyJWTname="vjwt-1"><Algorithms><Key>RSA-OAEP-256</Key><Content>A128GCM</Content></Algorithms><Type>Encrypted</Type><PrivateKey><Valueref="private.rsa_privatekey"/></PrivateKey><Subject>subject@example.com</Subject><Issuer>urn://apigee</Issuer><AdditionalHeaders><Claimname="moniker">Harvey</Claim></AdditionalHeaders><TimeAllowance>30s</TimeAllowance><Source>input_var</Source></VerifyJWT>

The sample above uses the<Algorithms> element, so it verifies an encryptedJWT. The<PrivateKey> element specifies the key that will be used to decrypt the JWT. Thereare other key elements as well. Which one you use depends on the algorithm specified by thevalue of<Algorithms>, as described in the next section.

Setting the key elements to verify an encrypted JWT

The following elements specify the key used to verify an encrypted JWT:

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

AlgorithmKey elements
RSA-OAEP-256
<PrivateKey>  <Value ref="private.rsa_privatekey"/></PrivateKey>

Note: The variable you specify must resolve to an RSA private key in PEM-encoded form.

  • ECDH-ES
  • ECDH-ES+A128KW
  • ECDH-ES+A192KW
  • ECDH-ES+A256KW
<PrivateKey>  <Value ref="private.ec_privatekey"/></PrivateKey>

Note: The variable you specify must resolve to an elliptic curve private key in PEM-encoded form.

  • A128KW
  • A192KW
  • A256KW
  • A128GCMKW
  • A192GCMKW
  • A256GCMKW
<SecretKeyencoding="base16|hex|base64|base64url"><Valueref="private.flow-variable-name-here"/></SecretKey>
  • PBES2-HS256+A128KW
  • PBES2-HS384+A192KW
  • PBES2-HS512+A256KW
<PasswordKey>  <Value ref="private.password-key"/>  <SaltLength>  <PBKDF2Iterations></PasswordKey>
dir
<DirectKey>  <Value encoding="base16|hex|base64|base64url" ref="private.directkey"/></DirectKey>

For more on the key requirements, seeAbout signature encryption algorithms.

Element reference

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

Note: Configuration will differ somewhat depending on the encryption algorithm you use. Refer to theSamples for examples that demonstrate configurations for specific use cases.

Attributes that apply to the top-level element

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

The following attributes are common to all policy parent elements.

AttributeDescriptionDefaultPresence
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 management UI proxy editor with a different, natural-language name.

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

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

falseOptional
enabled Set totrue to enforce the policy.

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

trueOptional
asyncThis attribute is deprecated.falseDeprecated

<DisplayName>

<DisplayName>Policy Display Name</DisplayName>

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

DefaultIf you omit this element, the value of the policy's name attribute is used.
PresenceOptional
TypeString

<Algorithm>

<Algorithm>HS256</Algorithm>

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

RS*/PS*/ES* algorithms employ a public/secret key pair, while HS* algorithms employ a shared secret. See also About signature encryption algorithms.

Note: Use exactly one of the elements<Algorithm> and<Algorithms>.

You can specify multiple values separated by commas. For example "HS256, HS512" or "RS256, PS256". However, you cannot combine HS* algorithms with any others or ES* algorithms with any others because they require a specific key type. You can combine RS* and PS* algorithms.

DefaultN/A
PresenceRequired
TypeString of comma-separated values
Valid valuesHS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512

<Algorithms>

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

Use the<Algorithms> element to verify an encrypted JWT. This element specifies the cryptographic algorithm for key encryption that must have been used when the encrypted JWT was created. It also optionally specifies the algorithm for content encryption.

Note: Use exactly one of the elements<Algorithm> and<Algorithms>.
DefaultN/A
PresenceRequired, when verifying an encrypted JWT
TypeComplex

Child elements of<Algorithms>

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

Child ElementRequired?Description
<Key>RequiredSpecifies the encryption algorithm for the key.
<Content>OptionalSpecifies the encryption algorithm for the content.

Verification will fail if:

  • The algorithm asserted in thealg property in the header of the encrypted JWT is different than the key encryption algorithm specified here in the<Key> element.
  • The policy specifies a<Content> element, and the algorithm asserted in theenc property in the header of the encrypted JWT is different than that specified in the<Content> element.

For example, to verify an encrypted JWT and check that the key algorithm isRSA-OAEP-256, and that the content algorithm isA128GCM:

  <Algorithms>    <Key>RSA-OAEP-256</Key>    <Content>A128GCM</Content>  </Algorithms>

Conversely, to verify an encrypted JWT and check that the key algorithm isRSA-OAEP-256, and not enforce a constraint on the content algorithm:

  <Algorithms>    <Key>RSA-OAEP-256</Key>  </Algorithms>

Key encryption algorithms

The following table lists the available algorithms for key encryption, as well as the type of key you must specify to verify a JWT using that key encryption algorithm.

Value of<Key> (key encryption algorithm)Key element required for verification
dir<DirectKey>
RSA-OAEP-256<PrivateKey>
  • 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
<PrivateKey>

SeeVerify an encrypted JWT for an example in which the key encryption algorithm isRSA-OAEP-256, so you use the<PrivateKey> element.

Content encryption algorithms

The VerifyJWT policy does not require that you specify an algorithm for content encryption. If you wish to specify the algorithm used for content encryption, do so with the<Content> child of the<Algorithms> element.

Regardless of the key encryption algorithm, the following algorithms - all symmetric and AES-based - are supported for content encryption:

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

<Audience>

<Audience>audience-here</Audience>or:<Audienceref='variable-name-here'/>

The policy verifies that the audience claim in the JWT matches the value specified in the configuration. If there is no match, the policy throws an error. This claim identifies the recipients that the JWT is intended for. This is one of the registered claims mentioned inRFC7519.

DefaultN/A
PresenceOptional
TypeString
Valid valuesA flow variable or string that identifies the audience.

<AdditionalClaims/Claim>

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

Validates that the JWT payload contains the specified additional claim(s) and that the asserted claim values match.

The<Claim> element supports the dynamic string substitution feature calledmessage templating.

An additional claim uses a name that is not one of the standard, registered JWT claim names. The value of a additional claim can be a string, a number, a boolean, a map, or an array. A map is simply a set of name/value pairs. The value for a claim of any of these types can be specified explicitly in the policy configuration, or indirectly via a reference to a flow variable.

Note: Do not use any of the registered claim names in this element. The registered claims are specified inRFC7519. They include: "iss", "sub", "aud", "iat", "exp", "nbf", and "jti".
DefaultN/A
PresenceOptional
TypeString, number, boolean, or map
ArraySet totrue to indicate if the value is an array of types. Default: false
Valid valuesAny value that you want to use for an additional claim.

The<Claim> element takes these attributes:

  • name - (Required) The name of the claim.Note: Do not use any of the registered claim names in this element. The registered claims are specified inRFC7519. They include: "iss", "sub", "aud", "iat", "exp", "nbf", and "jti".
  • ref - (Optional) The name of a flow variable. If present, the policy will use the value of this variable as the claim. If both aref 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 totrue 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 are determined at runtime.

For example:

<AdditionalClaims ref='json_claims'/>

Where the variablejson_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}}}

<AdditionalHeaders/Claim>

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

Validates that the JWT header contains the specified additional claim name/value pair(s) and that the asserted claim values match.

The<Claim> element supports the dynamic string substitution feature calledmessage templating.

An additionl claim uses a name that is not one of the standard, registered JWT claim names. The value of an additional claim can be a string, a number, a boolean, a map, or an array. A map is simply a set of name/value pairs. The value for a claim of any of these types can be specified explicitly in the policy configuration, or indirectly via a reference to a flow variable.

Note: Do not use any of the registered claim names in this element. The registered claims are specified inRFC7519. They include: "iss", "sub", "aud", "iat", "exp", "nbf", and "jti".
DefaultN/A
PresenceOptional
Type

String (default), number, boolean, or map.

The type defaults to String if no type is specified.

ArraySet totrue to indicate if the value is an array of types. Default: false
Valid valuesAny value that you want to use for an additional claim.

The<Claim> element takes these attributes:

  • name - (Required) The name of the claim.Note: Do not use any of the registered claim names in this element. The registered claims are specified inRFC7519. They include: "iss", "sub", "aud", "iat", "exp", "nbf", and "jti".
  • ref - (Optional) The name of a flow variable. If present, the policy will use the value of this variable as the claim. If both aref 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 totrue to indicate if the value is an array of types. Default: false.

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

<Id>

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

Verifies that the JWT has the specificjti 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 toRFC7519.

DefaultN/A
PresenceOptional
TypeString, or reference.
Valid valuesEither a string or the name of a flow variable containing the ID.

<IgnoreCriticalHeaders>

<IgnoreCriticalHeaders>true|false</IgnoreCriticalHeaders>

Set to false if you want the policy to throw an error when any header listed in thecrit header of the JWT is not listed in the<KnownHeaders> element. Set to true to cause the VerifyJWT policy to ignore thecrit header.

One reason to set this element to true is if you are in a testing environment and are not yet ready to handle a failure on a missing header.

Defaultfalse
PresenceOptional
TypeBoolean
Valid valuestrue or false

<IgnoreIssuedAt>

<IgnoreIssuedAt>true|false</IgnoreIssuedAt>

Set to false (default) if you want the policy to throw an error when a JWT contains aniat (Issued at) claim that specifies a time in the future. Set to true to cause the policy to ignoreiat during verification.

Defaultfalse
PresenceOptional
TypeBoolean
Valid valuestrue or false

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

Defaultfalse
PresenceOptional
TypeBoolean
Valid valuestrue or false

<Issuer>

<VerifyJWTname='VJWT-29'>...<!--verifythattheissclaimmatchesahard-codedvalue--><Issuer>issuer-string-here</Issuer>or:<!--verifythattheissclaimmatchesthevaluecontainedinavariable--><Issuerref='variable-containing-issuer'/>or:<!--verifyviaavariable;fallbacktoahard-codedvalueifthevariableisempty--><Issuerref='variable-containing-issuer'>fallback-value-here</Issuer>

The policy verifies that the issuer in the JWT (theiss claim) matches the string specified in the configuration element. Theiss claim is one of the registered claims mentioned inIETF RFC 7519.

DefaultN/A
PresenceOptional
TypeString, or reference
Valid valuesAny

<KnownHeaders>

<KnownHeaders>a,b,c</KnownHeaders>or:<KnownHeadersref='variable_containing_headers'/>

TheGenerateJWT policy uses the<CriticalHeaders> element to populate thecrit header in a JWT. For example:

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

The VerifyJWT policy examinescrit header in the JWT, if it exists, and for each header listed it checks that the<KnownHeaders> element also lists that header. The<KnownHeaders> element can contain a superset of the items listed incrit. It is only necessary that all the headers listed incrit are listed in the<KnownHeaders> element. Any header that the policy finds incrit that is not also listed in<KnownHeaders> causes the VerifyJWT policy to fail.

You can optionally configure the VerifyJWT policy to ignore thecrit header by setting the<IgnoreCriticalHeaders> element totrue.

Note:The VerifyJWT policy does not actually handle or process the headers listed by the<KnownHeaders> element. It is left for you later in the proxy or the backend to actually handle those headers.
DefaultN/A
PresenceOptional
TypeComma separated array of strings
Valid valuesEither an array or the name of a variable containing the array.

<MaxLifespan>

<VerifyJWTname='VJWT-62'>...<!--hard-codedlifespanof5minutes--><MaxLifespan>5m</MaxLifespan>or:<!--refertoavariable--><MaxLifespanref='variable-here'/>or:<!--attributetellingthepolicytouseiatratherthannbf--><MaxLifespanuseIssueTime='true'>1h</MaxLifespan>or:<!--useIssueTimeandref,andhard-codedfallbackvalue.--><MaxLifespanuseIssueTime='true'ref='variable-here'>1h</MaxLifespan>...

Configures the VerifyJWT policy to check that the lifespan of a token does not exceed a specified threshold. You can specify the threshold by using a number followed by a character, denoting the number of seconds, minutes, hours, days, or weeks. The following characters are valid:

  • s - seconds
  • m - minutes
  • h - hours
  • d - days
  • w - weeks

For example, you can specify one of the following values: 120s, 10m, 1h, 7d, 3w.

The policy computes the actual lifespan of the token by subtracting the not-before value(nbf) from the expiry value(exp). If eitherexp ornbf is missing, the policy throws a fault. If the token lifespan exceeds the specified timespan, the policy throws a fault.

You can set the optional attributeuseIssueTime totrue to use theiat value instead of thenbf value when computing the token lifespan.

The use of theMaxLifespan element is optional. If you use this element, you can use it only once.

<PrivateKey>

Use this element to specify the private key that can be used to verify a JWT encrypted with an asymmetric algorithm. A description of possible child elements follows.

<Password>

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

A child of the<PrivateKey> element. Specifies the password the policy should use to decrypt the private key, if necessary, when verifying an encrypted JWT. Use theref attribute to pass the password in a flow variable.

DefaultN/A
PresenceOptional
TypeString
Valid values A flow variable reference.

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

<Value>

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

Child of the<PrivateKey> element. Specifies a PEM-encoded private key that the policy will use to verify an encrypted JWT. Use theref attribute to pass the key in a flow variable.

DefaultN/A
PresenceRequired to verify a JWT that has been encrypted using an asymmetric key encryption algorithm.
TypeString
Valid values A flow variable containing a string representing a PEM-encoded RSA private key value.

Note: The flow variable must have the prefix "private". For example,private.mykey

<PublicKey>

Specifies the source for the public key used to verify a JWT signed with an asymmetric algorithm. Support algorithms include RS256/RS384/RS512, PS256/PS384/PS512, or ES256/ES384/ES512. A description of the possible child elements follows.

<Certificate>

<PublicKey>  <Certificateref="signed_public.cert"/></PublicKey>-or-<PublicKey>  <Certificate>-----BEGINCERTIFICATE-----certificatedata-----ENDCERTIFICATE-----  </Certificate></PublicKey>

A child of the<PublicKey> element. Specifies the signed certificate used as the source of the public key. Use theref attribute to pass the signed certificate in a flow variable, or specify the PEM-encoded certificate directly. Make sure to align the certificate data on the left as shown in the reference example.

DefaultN/A
PresenceOptional. To verify a JWT signed with an asymmetric algorithm, you must use the<Certificate>, the<JWKS>, or the<Value> element to supply the public key.
TypeString
Valid valuesA flow variable or string.

<JWKS>

  <PublicKey>    <JWKS …  > … </JWKS>  </PublicKey>

A child of the<PublicKey> element. Specifies a JWKS as a source of public keys. This will be a list of keys following the format described inIETF RFC 7517 - JSON Web Key (JWK).

If the inbound JWT bears a key ID which is present in the JWKS, then the policy will use the correct public key to verify the JWT signature. For details about this feature, see Using a JSON Web Key Set (JWKS) to verify a JWT.

If you fetch the value from a public URL, Apigee caches the JWKS for a period of 300 seconds. When the cache expires, Apigee fetches the JWKS again.

DefaultN/A
PresenceOptional. To verify a JWT signed with an asymmetric algorithm, you must use the<Certificate>, the<JWKS>, or the<Value> element to supply the public key.
TypeString
Valid values

You can specify the JWKS in one of four ways:

  • Literally, as a text value:

      <PublicKey>    <JWKS>{      "keys": [        {"kty":"RSA","e":"AQAB","kid":"b3918c88","n":"jxdm..."},        {"kty":"RSA","e":"AQAB","kid":"24f094d4","n":"kWRdbgMQ..."}      ]    }    </JWKS>  </PublicKey>
  • Indirectly, with theref attribute, specifying a flow variable:

    <PublicKey><JWKSref="variable-containing-jwks-content"/></PublicKey>

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

  • Indirectly via a static uri, with theuri attribute:

      <PublicKey>    <JWKS uri="uri-that-returns-a-jwks"/>  </PublicKey>
  • Indirectly via a dynamically-determined uri, with theuriRef attribute:

    <PublicKey><JWKSuriRef="variable-containing-a-uri-that-returns-a-jwks"/></PublicKey>

<Value>

<PublicKey>  <Valueref="public.publickeyorcert"/></PublicKey>-or-<PublicKey>  <Value>-----BEGINPUBLICKEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw2kPrRzcufvUNHvTH/WW...YOURPUBLICKEYMATERIALHERE....d1lH8MfUyRXmpmnNxJHAC2F73IyNZmkDb/DRW5onclGzxQITBFP3S6JXd4LNESJcTp705ec1cQ9Wp2Kl+nKrKyv1E5XxDQIDAQAB-----ENDPUBLICKEY-----  </Value></PublicKey>

A child of the<PublicKey> element. Specifies the public key to use to verify the signature on a signed JWT. Use theref attribute to pass the key in a flow variable, or specify the PEM-encoded key directly. Make sure to align the public key on the left as shown in the reference example.

DefaultN/A
PresenceOptional. To verify a JWT signed with an asymmetric algorithm, you must use the<Certificate>, the<JWKS>, or the<Value> element to supply the public key.
TypeString
Valid valuesA flow variable or string.

<RequiredClaims>

<VerifyJWTname='VJWT-1'>...<!--Directlyspecifythenamesoftheclaimstorequire--><RequiredClaims>sub,iss,exp</RequiredClaims>-or-<!--Specifytheclaimnamesindirectly,viaacontextvariable--><RequiredClaimsref='claims_to_require'/>...</VerifyJWT>

The<RequiredClaims> element is optional. It specifies a comma-separated list of names of claims that must be present in the JWT payload, when verifying a JWT. The element ensures that the presented JWT contains the required claims but does not validate the contents of the claims. If any of the listed claims are not present, the VerifyJWT policy will throw a fault at runtime.

DefaultN/A
PresenceOptional
TypeString
Valid valuesA comma-separated list of claim names.

<SecretKey>

<SecretKeyencoding="base16|hex|base64|base64url"><Valueref="private.your-variable-name"/></SecretKey>

The SecretKey element is optional. It specifies the secret key to use when verifying a signed JWT that uses a symmetric (HS*) algorithm or when verifying 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>:

ChildPresenceDescription
encoding (attribute)Optional

Specifies how the key is encoded in the referenced variable. By default, when noencoding 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.

<SecretKeyencoding="hex" >  <Value ref="private.secretkey"/></SecretKey>

In the above example, because the encoding ishex, if the contents of the variableprivate.secretkey is494c6f766541504973, the key will be decoded as a set of 9 bytes, which in hex will be49 4c 6f 76 65 41 50 49 73.

Note: Apigee enforces a minimum key strength. See the documentation for theValue element for details.
Value (element)Required

An encoded secret key. Specifies the secret key that will be used to verify the payload. Use theref attribute to provide the key indirectly via a variable, such asprivate.secret-key .

<SecretKey><Valueref="private.my-secret-variable"/></SecretKey>
Note: The variable name must include theprivate prefix as shown in the example above.

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.

<Source>

<Source>jwt-variable</Source>

If present, specifies the flow variable in which the policy expects to find the JWT to verify.

With this element, you can configure the policy to retrieve the JWT from a form or query parameter variable or any other variable. When this element is present, the policy will not strip anyBearer prefix that may be present. If the variable does not exist or if the policy does not find a JWT in the specified variable, the policy returns an error.

By default, when no<Source> element is present, the policy retrieves the JWT by reading the variablerequest.header.authorization and stripping theBearer prefix. If you pass the JWT in the Authorization header as a bearer token (with theBearer prefix), do not specify the<Source> element in the policy configuration. For example, you would use no<Source> element in the policy configuration if you pass the JWT in the Authorization header like this:

curl -v https://api-endpoint/proxy1_basepath/api1 -H "Authorization: Bearer eyJhbGciOiJ..."
Defaultrequest.header.authorization (See the note above for important information about the default).
PresenceOptional
TypeString
Valid valuesAn Apigee flow variable name.

<Subject>

<VerifyJWTname='VJWT-8'>...<!--verifythatthesubclaimmatchesahard-codedvalue--><Subject>subject-string-here</Subject>or:<!--verifythatthesubclaimmatchesthevaluecontainedinavariable--><Subjectref='variable-containing-subject'/>or:<!--verifyviaavariable;fallbacktoahard-codedvalueifthevariableisempty--><Subjectref='variable-containing-subject'>fallback-value-here</Subject>

The policy verifies that the subject in the JWT (thesub claim) matches the string specified in the policy configuration. Thesub claim is one of the registered claims described inRFC7519.

DefaultN/A
PresenceOptional
TypeString
Valid valuesAny value uniquely identifying a subject.

<TimeAllowance>

<VerifyJWTname='VJWT-23'>...<!--configureahard-codedtimeallowanceof20seconds--><TimeAllowance>20s</TimeAllowance>or:<!--refertoavariablecontainingthetimeallowance--><TimeAllowanceref='variable-containing-time-allowance'/>or:<!--refertoavariable;fallbacktoahard-codedvalueifthevariableisempty--><TimeAllowanceref='variable-containing-allowance'>30s</TimeAllowance>

The "grace period" for times, to account for clock skew between the issuer and verifier of a JWT. This will apply to both the expiry (theexp claim) as well as the not-before-time (thenbf claim). For example, if the time allowance is configured to be30s, then an expired JWT would be treated as still valid, for 30 seconds after the asserted expiry. The not-before-time will be evaluated similarly.

Default0 seconds (no grace period)
PresenceOptional
TypeString
Valid values A timespan expression, or a reference to a flow variable containing an expression. Time spans can be specified by a positive integer followed by one character indicating a time unit, as follows:
  • s = seconds
  • m = minutes
  • h = hours
  • d = days

<Type>

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

Describes whether the policy verifies 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> isSigned, the policy verifies a signed JWT, and the<Algorithm> element must be present.
    • If the value of<Type> isEncrypted, the policy verifies 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> isSigned.
    • If the<Algorithms> element is present, the policy assumes<Type> isEncrypted.
  • If neither<Algorithm> nor<Algorithms> is present, the configuration is invalid.
DefaultN/A
PresenceOptional
TypeString
Valid valuesEitherSigned orEncrypted

Flow variables

Upon success, theVerify JWT andDecode JWT policies set context variables according to this pattern:

jwt.{policy_name}.{variable_name}

For example, if the policy name isjwt-parse-token , then the policy will store the subject specified in the JWT to the context variable namedjwt.jwt-parse-token.decoded.claim.sub. (For backward compatibility, it will also be available injwt.jwt-parse-token.claim.subject)

Variable nameDescription
claim.audienceThe JWT audience claim. This value may be a string, or an array of strings.
claim.expiryThe expiration date/time, expressed in milliseconds since epoch.
claim.issuedatThe Date the token was issued, expressed in milliseconds since epoch.
claim.issuerThe JWT issuer claim.
claim.notbeforeIf the JWT includes a nbf claim, this variable will contain the value, expressed in milliseconds since epoch.
claim.subjectThe JWT subject claim.
claim.nameThe value of the named claim (standard or additional) in the payload. One of these will be set for every claim in the payload.
decoded.claim.nameThe JSON-parsable value of the named claim (standard or additional) in the payload. One variable is set for every claim in the payload. For example, you can usedecoded.claim.iat to retrieve the issued-at time of the JWT, expressed in seconds since epoch. While you can also use theclaim.name flow variables, this is the recommended variable to use to access a claim.
decoded.header.nameThe JSON-parsable value of a header in the payload. One variable is set for every header in the payload. While you can also use theheader.name flow variables, this is the recommended variable to use to access a header.
expiry_formattedThe expiration date/time, formatted as a human-readable string. Example: 2017-09-28T21:30:45.000+0000
header.algorithmThe signing algorithm used on the JWT. For example, RS256, HS384, and so on. See(Algorithm) Header Parameter for more.
header.kidThe Key ID, if added when the JWT was generated. See also "Using a JSON Web Key Set (JWKS)" atJWT policies overview to verify a JWT. See(Key ID) Header Parameter for more.
header.typeWill be set toJWT.
header.nameThe value of the named header (standard or additional). One of these will be set for every additional header in the header portion of the JWT.
header-jsonThe header in JSON format.
is_expiredtrue or false
payload-claim-namesAn array of claims supported by the JWT.
payload-json
The payload in JSON format.
seconds_remainingThe number of seconds before the token will expire. If the token is expired, this number will be negative.
time_remaining_formattedThe time remaining before the token will expire, formatted as a human-readable string. Example: 00:59:59.926
valid In the case of VerifyJWT, this variable will be true when the signature is verified, and the current time is before the token expiry, and after the token notBefore value, if they are present. Otherwise false.

In the case of DecodeJWT, this variable is not set.

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, seeWhat you need to know about policy errors andHandling faults.

Runtime errors

These errors can occur when the policy executes.

Fault codeHTTP statusOccurs when
steps.jwt.AlgorithmInTokenNotPresentInConfiguration401Occurs when the verification policy has multiple algorithms.
steps.jwt.AlgorithmMismatch401The algorithm specified in theGenerate policy did not match the one expected in theVerify policy. The algorithms specified must match.
steps.jwt.FailedToDecode401The policy was unable to decode the JWT. The JWT is possibly corrupted.
steps.jwt.GenerationFailed401The policy was unable to generate the JWT.
steps.jwt.InsufficientKeyLength401For 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.InvalidClaim401For a missing claim or claim mismatch, or a missing header or header mismatch.
steps.jwt.InvalidConfiguration401Both the<Algorithm> and<Algorithms> elements are present.
steps.jwt.InvalidCurve401The curve specified by the key is not valid for the Elliptic Curve algorithm.
steps.jwt.InvalidIterationCount401The iteration count that was used in the encrypted JWT is not equal to the iteration count specified in the VerifyJWT policy configuration. This applies only to JWT that use<PasswordKey>.
steps.jwt.InvalidJsonFormat401Invalid JSON found in the header or payload.
steps.jwt.InvalidKeyConfiguration401JWKS in the<PublicKey> element is invalid. The reason could be that the JWKS URI endpoint is not reachable from the Apigee instance. Test connectivity to the endpoint by creating a passthrough proxy and using the JWKS endpoint as a target.
steps.jwt.InvalidSaltLength401The salt length that was used in the encrypted JWT is not equal to the salt length specified in the VerifyJWT policy configuration. This applies only to JWT that use<PasswordKey>.
steps.jwt.InvalidPasswordKey401The specified key specified did not meet the requirements.
steps.jwt.InvalidPrivateKey401The specified key specified did not meet the requirements.
steps.jwt.InvalidPublicKey401The specified key specified did not meet the requirements.
steps.jwt.InvalidSecretKey401The specified key specified did not meet the requirements.
steps.jwt.InvalidToken401This error occurs when the JWT signature verification fails.
steps.jwt.JwtAudienceMismatch401The audience claim failed on token verification.
steps.jwt.JwtIssuerMismatch401The issuer claim failed on token verification.
steps.jwt.JwtSubjectMismatch401The subject claim failed on token verification.
steps.jwt.KeyIdMissing401TheVerify policy uses a JWKS as a source for public keys, but the signed JWT does not include akid property in the header.
steps.jwt.KeyParsingFailed401The public key could not be parsed from the given key information.
steps.jwt.NoAlgorithmFoundInHeader401Occurs when the JWT contains no algorithm header.
steps.jwt.NoMatchingPublicKey401TheVerify policy uses a JWKS as a source for public keys, but thekid in the signed JWT is not listed in the JWKS.
steps.jwt.SigningFailed401In GenerateJWT, for a key less than the minimum size for the HS384 or HS512 algorithms
steps.jwt.TokenExpired401The policy attempts to verify an expired token.
steps.jwt.TokenNotYetValid401The token is not yet valid.
steps.jwt.UnhandledCriticalHeader401A header found by the Verify JWT policy in thecrit header is not listed inKnownHeaders.
steps.jwt.UnknownException401An unknown exception occurred.
steps.jwt.WrongKeyType401Wrong 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.

Tip: Need help resolving an error? Clickin the Fix column for detailed troubleshooting information.
Error nameCauseFix
InvalidNameForAdditionalClaimThe 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, orjti.
InvalidTypeForAdditionalClaimIf the claim used in the child element<Claim> of the<AdditionalClaims> element is not of typestring,number,boolean, ormap, the deployment will fail.
MissingNameForAdditionalClaimIf the name of the claim is not specified in the child element<Claim> of the<AdditionalClaims> element, the deployment will fail.
InvalidNameForAdditionalHeaderThis error ccurs when the name of the claim used in the child element<Claim> of the<AdditionalClaims> element is eitheralg ortyp.
InvalidTypeForAdditionalHeaderIf the type of claim used in the child element<Claim> of the<AdditionalClaims> element is not of typestring,number,boolean, ormap, the deployment will fail.
InvalidValueOfArrayAttributeThis error occurs when the value of the array attribute in the child element<Claim> of the<AdditionalClaims> element is not set totrue orfalse.
InvalidValueForElementIf the value specified in the<Algorithm> element is not a supported value, the deployment will fail.
MissingConfigurationElementThis 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.
InvalidKeyConfigurationIf the child element<Value> is not defined in the<PrivateKey> or<SecretKey> elements, the deployment will fail.
EmptyElementForKeyConfigurationIf the ref attribute of the child element<Value> of the<PrivateKey> or<SecretKey> elements is empty or unspecified, the deployment will fail.
InvalidConfigurationForVerifyThis error occurs if the<Id> element is defined within the<SecretKey> element.
InvalidEmptyElementThis error occurs if the<Source> element of the Verify JWT policy is empty. If present, it must be defined with an Apigee flow variable name.
InvalidPublicKeyValueIf the value used in the child element<JWKS> of the<PublicKey> element does not use a valid format as specified inRFC 7517, the deployment will fail.
InvalidConfigurationForActionAndAlgorithmIf the<PrivateKey> element is used with HS Family algorithms or the<SecretKey> element is used with RSA Family algorithms, the deployment will fail.

Fault variables

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

VariablesWhereExample
fault.name="fault_name"fault_name is the name of the fault, as listed in theRuntime errors table above. The fault name is the last part of the fault code.fault.name Matches "InvalidToken"
JWT.failedAll 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 theerrorcode part of the error response. Do not rely on the text in thefaultstring, 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>

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-19 UTC.