JWT Validation Policy | MuleSoft Documentation
# JWT Validation Policy
**Policy name** |  JWT Validation  
---|---  
Validates a JWT  
**First Flex Gateway version available**  
**Returned Status Codes**  
400 - Token was not provided in the request. |  Signature was not validated, or is invalid.  
---  
Some of the required claims are not present or their validation failed.  
Failed to parse the token.  
## Summary
JSON Web Token (JWT) is a URL-secure method of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS), or as a JSON web encryption (JWE) structure in plain text. This enables the claims to be digitally signed and integrity protected with a message authentication code (MAC). Because the token is signed, you can trust the information and its source.
The JWT Validation policy validates the signature of the token and asserts the values of the claims of all incoming requests by using a JWT with JWS format. The policy does not validate JWT that uses JWE.
## Configuring Policy Parameters
### Flex Gateway Local Mode
In Local Mode, you apply the policy to your API via declarative configuration files. Refer to the following policy definition and table of parameters:
```
- policyRef:
  name: jwt-validation-flex
 config:
```

Parameter | Required or Optional | Default Value | Description  
---|---|---|---  
`signingMethod` |  String containing the key signing method. Supported values: `rsa`, `hmac`, `es`, `none`  
`signingKeyLength` |  Number indicating key length. Supported values are 256, 384, 512. For ES method, Flex Gateway supports 256 and 384 key lengths.  
`your-(256|384|512)-bit-secret/your-public-pem-certificate`  
`httpBearerAuthenticationHeader`  
`jwtKeyOrigin`  
`http://your-jwks-service.example:80/base/path` |  JWKS server URLs that contain the public keys for the signature validation. Configure multiple JWKS servers with a comma-separated list of the URLs.  
`jwksServiceTimeToLive` |  Amount of time, in minutes, during which the policy considers the JWKS valid.  
`jwksServiceConnectionTimeout` |  Maximum time, in milliseconds, to wait for a response from each JWKS service when authenticating the access token validation endpoint.  
`validateAudClaim`  
`mandatoryAudClaim`  
`mandatoryNbfClaim`  
`mandatoryExpClaim`  
`supportedAudiences` |  Empty string  
`validateCustomClaim`  
`mandatoryCustomClaims` |  Empty array  
`nonMandatoryCustomClaims` |  Empty array  
`jwtExpression` |  `#[attributes.headers['jwt']]`  
`skipClientIdValidation` |  This parameter must be set to `true` in Local Mode.  
`clientIdExpression` |  `#[vars.claimSet.client_id]`  
### Managed Flex Gateway and Flex Gateway Connected Mode
When you apply the policy to your API instance from the UI, the following parameters are displayed:
Element | Description | Example  
---|---|---  
JWT Origin | Specifies from where in the request the JWT will be extracted: * HTTP Bearer Authentication Header * Custom Expression If you set this field to `HTTP Bearer Authentication Header`, the JWT is expected as Bearer. If you set this field to `Custom Expression`, provide a DataWeave expression that returns the token.  
Token Expression | If you set the JWT Origin to `Custom Expression`, type the DataWeave expression returning the JWT here. | `#[attributes.headers['jwt']]` This expression searches the JWT in the header named `jwt`.  
JWT Signing Method | Specify the signing method expected in the incoming JWT. The policy rejects the token if the JWT has a different signing method. | RSA, HMAC, ES, None  
JWT Signing Key Length | Specify the length of the key (in the case of the HMAC algorithm) or the algorithm (in the case of RSA) used for the signing method. Ignore this field if you selected **none** as JWT Signing Method. | 256, 384, 512. For ES method, Flex Gateway only supports 256 and 384 key lengths.  
JWT Key Origin | Specifies where to obtain the key for the Signature validation. You can provide the key in the policy by selecting the **Text** option or by obtaining it from a **JWKS**. Ignore this field if you selected **none** as JWT Signing Method.  
This field appears if you selected **Text** as JWT Key Origin. Use this field to provide the key used to check the signature of the token. Ignore this field if you selected **none** as JWT Signing Method. | Enter a 32, 48, or 64 character string shared secret for HMAC, a 32 character string shared secret for ES, or the PEM Public Key without the header and footer for RSA.  
JWKS URL | This field appears if you selected the **JWKS** method as JWT Key Origin. Ignore this field if you selected **none** as JWT Signing Method. | JWKS server URLs that contain the public keys for the signature validation. Configure multiple JWKS servers with a comma-separated list of the URLs.  
JWKS Caching Time To Live | Amount of time, in minutes, that the JWKS is valid. When the JWKS expires, the policy retrieves the JWKS from each JWKS server again. The default value is 60 minutes. Ignore this field if you selected **none** as JWT Signing Method. | This field input is the amount of time, in minutes, during which the policy considers the JWKS valid.  
JWKS Service connection timeout (milliseconds) | Maximum time, in milliseconds, to wait for a response from each JWKS service when authenticating the access token validation endpoint. The default value is 10 seconds.  
Skip Client ID Validation | If you check this field, the policy does not verify that the client ID extracted from the JWT matches a valid client application of the API.  
Client ID Expression | If Skip Client Id Validation is not set, the client ID needs to be extracted from the token. | By default, the value will be extracted using the expression `#[vars.claimSet.client_id]` as specified in the Oauth 2.0 token exchange draft.  
Validate Audience Claim | Indicates that the policy should check for the validity of the audience claim. You can set this "Mandatory" if you select **Audience Claim Mandatory**.  
Validate Expiration Claim | Indicates that the policy should check for the validity of the expiration claim. You can set this claim as "Mandatory" by selecting **Expiration Claim Mandatory**.  
Validate Not Before Claim | Indicates that the policy should check for the validity of the Not Before claim. You can set this claim as "Mandatory" by selecting **Not Before Claim Mandatory**  
Validate Custom Claim | Enables the usage of custom validations in the policy. The JWT will be valid only if all DataWeave expressions are fulfilled. | The policy provides a _claimSet_ variable that contains all the claims present in the incoming JWT. For example: `foo : #[vars.claimSet.foo == 'fooValue']` Note that all DataWeave expressions must return a boolean value or they will always fail.  
## How This Policy Works
The policy validates claims and signatures differently, as explained in this section.
### Validating Signatures
The policy validates the signature of the JWT based on the values specified in the policy configuration. If the algorithm specified in the policy configuration does not match with the token, or if the signature of the token is invalid, all JWTs are rejected by the policy. If no algorithm is specified, the policy matches every signed and unsigned token.
The algorithms that support signature verification are:
  * **Symmetric algorithms** - HMAC using SHA-256, SHA-384, and SHA-512.
  * **Asymmetric algorithms** - ES and RSA using SHA-256, SHA-384, and SHA-512.
  * **None** - No signature validation.


For more information about the algorithms in a JWS structure, refer to the JWA RFC standard.
### Validating Claims
Claim validations enable you to choose the conditions under which a token received in the policy is rejected. The following registered claim validations are provided by default:
  * **aud** : The Audience validation specifies that a token must be rejected if it does not contain at least one of the values defined.
  * **exp** : The Expiration validation specifies that a token must be rejected if its date is past the validation date.
  * **nbf** : The Not before validation specifies that the token must be rejected if the validation time is before the time the token has.


In addition to these _provided claims_ , you can also specify other claims to use in your validations. For all claims, _Registered_ or _Custom_ , you must provide the following details:
  * The name of the claim you want to validate. For example **iss** , for the issuer of the token.
  * The value used to test. You can provide a simple literal value if you only need to verify it, or you can provide a DataWeave expression for more complex comparisons.
For more information about the algorithms in a JWS structure, refer to the JWA RFC standard.
### Validating Claims
Claim validations enable you to choose the conditions under which a token received in the policy is rejected. The following registered claim validations are provided by default:
  * **aud** : The Audience validation specifies that a token must be rejected if it does not contain at least one of the values defined.
  * **exp** : The Expiration validation specifies that a token must be rejected if its date is past the validation date.
  * **nbf** : The Not before validation specifies that the token must be rejected if the validation time is before the time the token has.


In addition to these _provided claims_ , you can also specify other claims to use in your validations. For all claims, _Registered_ or _Custom_ , you must provide the following details:
  * The name of the claim you want to validate. For example **iss** , for the issuer of the token.
  * The value used to test. You can provide a simple literal value if you only need to verify it, or you can provide a DataWeave expression for more complex comparisons.


You can define each claim validation as mandatory or non-mandatory. If a claim is defined as mandatory and is not present in the incoming JWT, the policy rejects this token. If a claim is defined as non-mandatory and is not present in the incoming JWT, the policy does not reject the token for that specific validation. For both cases, if a claim is present, the policy validates the token value. If the validation fails, the JWT will be rejected.
### Propagating Claims
After the policy parses and validates the JWT, the claims are propagated to downstream policies and flows through the **claims** property in the authentication object.
To access the claim values you can use the following Dataweave 2.0 expression by replacing `<claimName>` with the name of the desired claim to access:
`#[authentication.properties.claims.<claimName>]`
The JWT is also propagated downstream, and you can access it by using the following Dataweave 2.0 expression:
`#[authentication.properties.jwt]`
#### Propagating Client ID
If Client ID validation is enabled, the Client ID is propagated as a claim and as a reserved authentication property. Access the property by using the following DataWeave expression:
`#[authentication.clientId]`
### Retry Mechanism
If you selected JSON Web Key Set (JWKS) as JWT Key Origin, the policy uses a retry mechanism to handle failed JWKS fetches. Every time the cached JWKS expires or is absent and a new request is triggered, a request is sent to each JWKS service. If a request fails, a sequence of asynchronous requests with an exponential backoff delay is sent to the failed JWKS service until a new JWKS is obtained and cached again.
Until the recaching finishes, the expired JWKS is used to process the request, and a `503` error is returned if no request is found. Using an expired JWKS enables you to apply cached values in upcoming requests, even if the previous requests failed.
## Obtain a Policy Compatible PEM Public Key
If you have a preexisting RSA key in an unsupported format that you want to use, first covert the key to a PEM public key. The JWT policy uses public RSA key in PEM format.
**Task Prerequisite**
Before you convert your existing key:
  1. Obtain the `public.pem` key.
  2. Before you paste the key to the policy configuration, remove the **-----BEGIN PUBLIC KEY-----** header and the **-----END PUBLIC KEY-----** footer.


The following table provides instructions for how to convert your existing key based on its current format:
Starting Point | Procedure  
---|---  
No previous certificate | 
  1. Generate the private RSA key `openssl genrsa -out key.pem 2048`
  2. Extract the public key from the generated private key **key.pem** `openssl rsa -in key.pem -outform PEM -pubout -out public.pem`
  3. The public key will be in the file public.pem

  
PEM Certificate | 
  1. Extract the public key from the PEM certificate `openssl x509 -inform pem -in cert.pem -pubkey -noout > public.pem`
  2. The public key will be in the file public.pem

  
DER Certificate | 
  1. Extract the public key from the DER certificate `openssl x509 -inform der -in cert.crt -pubkey -noout > public.pem`
  2. The public key will be in the file public.pem

  
x5c field from JWKS | 
  1. Copy the first certificate from the chain and decode it `echo <certificateString> | base64 -D > cert.crt` (replace `<certificateString>` with the copied value)
  2. Extract the public key from the DER certificate `openssl x509 -inform der -in cert.crt -pubkey -noout > public.pem`
  3. The public key will be in the file public.pem