Author: Jitendra Bafna
Introduction
JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between the 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) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code(MAC) and/or encrypted.
- JWTs are stateless, making tokens easier to manage.
- JWTs can be used to transfer claims securely between parties.
- JWTs are scalable.
- The payload of a token can be expanded to increase new claims easily.
- JWTs are decoupled in nature allowing authentication to happen on a different server.
- The tokens are compact. JSON format makes the token less verbose than XML. The smaller size allows easier transmission over HTTP.
- JWTs are JSON-based and can be easily parsed by multiple receiving systems, especially mobiles. This enables an industry-wide adoption.
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.


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, 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.
Element | Description | Example |
JWT Origin | Specifies from where in the request the JWT will be extracted: * Bearer Authentication Header * Custom ExpressionIf you set it to Bearer Authentication Header, the JWT will be expected as Bearer.If you set this field to Custom Expression, a DataWeave Expression returning the token must be provided. | |
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, 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. | |
JWT Key Origin | Specifies where to obtain the key for the Signature validation.You can provide the key in the policy selecting the Text option or obtain it from JWKS.Ignore this field if you selected none as the JWT Signing Method. | |
JWT Key | This field appears if you select 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 the JWT Signing Method. | A 32, 48 or 64 characters long shared secret in case HMAC was the selected JWT Signing Method or the PEM Public Key without the header nor the footer in case of selecting RSA. |
JWKS URL | This field appears if you selected the JWKS method as JWT Key Origin.Ignore this field if you selected none as the JWT Signing Method. | The URL to the JWKS server. |
JWKS Caching Time To Live | The URL to the JWKS server that contains the public keys for the signature validation.Ignore this field if you selected none as the JWT Signing Method. | This field input is the amount of time, in minutes, during which the policy considers the JWKS valid. |
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. | By default, the value will be extracted using the expression #[vars.claimSet.client_id] |
Client ID Expression | If Skip Client Id Validation is not set, the client ID needs to be extracted from the token. | |
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’] |
There are various attributes required to enforce jwt validation policy.
Applying the JWT Validation Policy Using API Manager API
First we need to identify which API can be used to apply the policies. So, mulesoft provided a developer portal which can be used to fetch details about policies API.
https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/api-manager-api/minor/1.0/pages/Applying_a_policy/

Policies API Url
https://anypoint.mulesoft.com/apimanager/api/v1/organizations/{organizationId}/environments/{environmentId}/apis/{environmentApiId}/policies
We need to pass organizationId, environmentId and apiId in above url as uri parameter.
Fetching Organization Id
To fetch OrganizationId, Navigate to Access Management ⇒ Organization and Click on your organization and it will open pop-up windows which can provide OrganizationId and it can be used in the URI parameter of policies API.

Fetching Environment Id
To fetch EnvironmentId, Navigate to Access Management ⇒ Environment and Click on your environment (i.e. Sandbox) and it will open pop-up windows and we can get environmentId in url and it can be used in the URI parameter of policies API.

Fetching API Id
For fetching APIId, Navigate To API Manager in AnyPoint Platform and select the API for which you need to apply the policy and you can see API Id.

Now, we have fetched the organizationId, environmentId and apiId that needs to be passed to policies API as uri parameters.
We will be also requiring an access token that needs to be passed in the Authorization header of Policies API request.
Generating Access Token
MuleSoft provides a separate API for generating access token and for doing that you need to pass username and password in body.
You can use curl utility or postman to generate the token.
$ curl -H "Content-Type: application/json" -X POST -d '{"username":"<<Anypoint_Username>>","password":"<<Anypoint_Password>>"}' https://anypoint.mulesoft.com/accounts/login
Response
{ "access_token": "0cf70dc0-1982-42b5-8140-836048c15ce8", "token_type": "bearer", "redirectUrl": "/home/" }
You can also use postman to generate the token.

Applying the Policy Using API Manager API
First we need to identify what attributes need to pass for applying jwt validation policy.
Go To exchange and search for “Jwt Validation Policy Template”.
https://anypoint.mulesoft.com/exchange/68ef9520-24e9-4cf2-b2f5-620025690913/jwt-validation/

Click on “API Gateway JWT Validation template”.

Now Download as Policy definition and this will download a yaml file that will provide all attributes details that we need to pass.
Now you can use CURL to apply policy by calling policies API.
curl -X POST \
https://anypoint.mulesoft.com/apimanager/api/v1/organizations/:organizationId/environments/:environmentId/apis/:apiInstanceId/policies \
-H 'authorization: Bearer 0cf70dc0-1982-42b5-8140-836048c15ce8 \
-H 'content-type: application/json' \
-d '{
"configurationData":{
"jwtOrigin":"httpBearerAuthenticationHeader",
"jwtExpression":"#[attributes.headers['jwt']]",
"signingMethod":"rsa",
"signingKeyLength":"256",
"jwtKeyOrigin":"jwks",
"textKey":"Text Data",
"jwksUrl":"https://example.okta.com/oauth2/default/v1/keys",
"jwksServiceTimeToLive":60,
"skipClientIdValidation":true,
"clientIdExpression":"#[vars.claimSet.client_id]",
"validateAudClaim":false,
"mandatoryAudClaim":false,
"supportedAudiences":"aud.example.com",
"mandatoryExpClaim":false,
"mandatoryNbfClaim":false,
"validateCustomClaim":true,
"mandatoryCustomClaims":[{"key":"scope","value":"#[vars.claimSet.scope='API_READ']"}]
},
"policyTemplateId":"jwt-validation",
"assetId":"jwt-validation",
"assetVersion":"1.1.2",
"groupId":"68ef9520-24e9-4cf2-b2f5-620025690913"
}'
You need to pass organizationId, environmentId and apiId that we have fetched above. Currently we have a placeholder in curl policies api.
You can use postman also to call policies api.

{
"configurationData":{
"jwtOrigin":"httpBearerAuthenticationHeader",
"jwtExpression":"#[attributes.headers['jwt']]",
"signingMethod":"rsa",
"signingKeyLength":"256",
"jwtKeyOrigin":"jwks",
"textKey":"Text Data",
"jwksUrl":"https://example.okta.com/oauth2/default/v1/keys",
"jwksServiceTimeToLive":60,
"skipClientIdValidation":true,
"clientIdExpression":"#[vars.claimSet.client_id]",
"validateAudClaim":false,
"mandatoryAudClaim":false,
"supportedAudiences":"aud.example.com",
"mandatoryExpClaim":false,
"mandatoryNbfClaim":false,
"validateCustomClaim":true,
"mandatoryCustomClaims":[{"key":"scope","value":"#[vars.claimSet.scope='API_READ']"}]
},
"policyTemplateId":"jwt-validation",
"assetId":"jwt-validation",
"assetVersion":"1.1.2",
"groupId":"68ef9520-24e9-4cf2-b2f5-620025690913"
}
Video link:
This is a very useful utility when you need to apply policies via CI/CD and now you know how to apply jwt validation policy using API Manager API.