You're viewing Apigee Edge documentation.
Go to the
Apigee X documentation. info
What
Generates a signed 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.
Video
Watch a short video to learn how to generate a signed JWT.
Samples
Generate a JWT signed with the 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, Edge 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> <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>
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-edge-JWT-policy-test", "aud" : "show", "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.
Generate a JWT signed with the 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. See the video above for a complete example, including how to make a request to the policy.
When this policy action is triggered, Edge 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"> <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>
Setting the key elements
The elements that you use to specify the key used to generate the JWT depend on the chosen algorithm, as shown in the following table:
Algorithm | Key elements | |
---|---|---|
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> The |
|
*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 the Samples 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 Edge management UI enforces additional
restrictions, such as automatically removing characters that are not alphanumeric.
Optionally, use the |
N/A | Required |
continueOnError |
Set to false to return an error when a policy fails. This is expected
behavior for most policies.
Set to |
false | Optional |
enabled |
Set to true to enforce the policy.
Set to |
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 management 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 encryption algorithm to sign the token.
Default | N/A |
Presence | Required |
Type | String |
Valid values | HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512 |
<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.
<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” ], }
At runtime, 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.
<ExpiresIn>
<ExpiresIn>time-value-here</ExpiresIn>
Specifies the lifespan of the JWT in milliseconds, seconds, minutes, hours, or days.
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:
For example, an |
<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) |
<PrivateKey/Id>
<PrivateKey> <Id ref="flow-variable-name-here"/> </PrivateKey> or <PrivateKey> <Id>your-id-value-here</Id> </PrivateKey>
Specifies the key ID (kid) to include in the JWT header. Use only when the algorithm is one of RS256/RS384/RS512, PS256/PS384/PS512, or ES256/ES384/ES512.
Default | N/A |
Presence | Optional |
Type | String |
Valid values | A flow variable or string |
<PrivateKey/Password>
<PrivateKey> <Password ref="private.privatekey-password"/> </PrivateKey>
Specify the password the policy should use to decrypt the private key, if necessary. Use the ref attribute to pass the key in a flow variable. Use only when the algorithm is one of RS256/RS384/RS512, PS256/PS384/PS512, or ES256/ES384/ES512.
Default | N/A |
Presence | Optional |
Type | String |
Valid values |
A flow variable reference.
Note: You must specify a flow variable. Edge 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, |
<PrivateKey/Value>
<PrivateKey> <Value ref="private.variable-name-here"/> </PrivateKey>
Specifies a PEM-encoded private key used to sign the JWT. Use the ref attribute to pass the key in a flow variable. Use only when the algorithm is one of RS256/RS384/RS512, PS256/PS384/PS512, or ES256/ES384/ES512.
Default | N/A |
Presence | Required to generate a JWT using the RS256 algorithm. |
Type | String |
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,
|
<SecretKey/Id>
<SecretKey> <Id ref="flow-variable-name-here"/> </SecretKey> or <SecretKey> <Id>your-id-value-here</Id> </SecretKey>
Specifies the key ID (kid) to include in the JWT header of a JWT signed with an HMAC algorithm. Use only when the algorithm is one of HS256/HS384/HS512.
Default | N/A |
Presence | Optional |
Type | String |
Valid values | A flow variable or string |
<SecretKey/Value>
<SecretKey> <Value ref="private.your-variable-name"/> </SecretKey>
Provides the secret key used to verify or sign tokens with an HMAC algorithm. Use only when the algorithm is one of HS256/HS384/HS512. Use the ref attribute to pass the key in a flow variable.
Edge 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.
Default | N/A |
Presence | Required for HMAC algorithms. |
Type | String |
Valid values |
A flow variable referring to a string
Note: If a flow variable, it must have the prefix "private". For
example, |
<Subject>
<Subject>subject-string-here</Subject>
<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 RFC7519.
Default | N/A |
Presence | Optional |
Type | String |
Valid values | Any value uniquely identifying a subject or a flow variable referring to a value. |
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 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 .
|
build |
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.
|
build |
MissingNameForAdditionalClaim |
If the name of the claim is not specified in the child element <Claim>
of the <AdditionalClaims> element, the deployment will fail.
|
build |
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 .
|
build |
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.
|
build |
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 .
|
build |
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.
|
build |
InvalidValueForElement |
If the value specified in the <Algorithm> element is not a supported value,
the deployment will fail.
|
build |
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.
|
build |
InvalidKeyConfiguration |
If the child element <Value> is not defined in the <PrivateKey>
or <SecretKey> elements, the deployment will fail.
|
build |
EmptyElementForKeyConfiguration |
If the ref attribute of the child element <Value> of the <PrivateKey>
or <SecretKey> elements is empty or unspecified, the deployment will fail.
|
build |
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.) .
|
build |
InvalidSecretInConfig |
This error occurs if the child element <Value> of the <PrivateKey>
or <SecretKey> elements does not contain the private prefix (private.) .
|
build |
InvalidTimeFormat |
If the value specified in the<NotBefore> element does not use a
supported format, the deployment will fail.
|
build |
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
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>