Creating a JSON Web Token for a Virtual Service
search cancel

Creating a JSON Web Token for a Virtual Service


Article ID: 203569


Updated On:


Service Virtualization


Have anyone come across JSON Web Token (JWT) access token creation dynamically based on incoming request?
Need to create a new access token (using JWT) every time a particular service is called and send the access token back in the response.


DevTest 10.6
Service Virtualization




There is no OOB solution for this. However with scripting, the functionality can be achieved.

The below is an example and may not work in a client's environment exactly but can be modified.

Making the assumption that there is already a virtual service configured with the JSON DPH and incoming request has an argument called "username". 

Add a Request Data Copier DPH after the JSON DPH in the listen step, and copy all arguments to properties using the prefix "request_". So now during execution, you have the property "request_username" available inside your script. 

To avoid hardcoded JWT content, create 2 properties in your config file as below:

  • "JWT_Header"= { "typ": "JWT", "alg": "HS256" }
  • "JWT_Payload"= { "subscriptionAccountNumber": "1234567", "status": "ACTIVE", "userEmail": "{{request_username}}", "name": "John Doe", "subscriptionId": "001" }


And also need to make the secret key available, so assuming below is provided in config file (as an example below):

  • "JWT_SecretKey"0393e944ee8108bb66fc9fa4f99f9c862481e9e0519e18232ba61b0767eee8c6


The Response in your VSI should look like:


  "token_type": "Bearer",

  "expires_in": 7200,

  "authToken": "{{JWT_Token}}",

  "scope": "abc1"



Then add a script step to your VSM with following script:


import javax.crypto.spec.SecretKeySpec;

import javax.crypto.Mac;

import java.util.Base64;


       // Encode the JWT_Header

       String encodedJWT_header = Base64.getUrlEncoder().encodeToString(JWT_Header.getBytes());


       // Replace userEmail in JWT_Payload with request value, then encode JWT_Payload

       String parsedJWT_Payload = testExec.parseInState(JWT_Payload);

       String encodedJWT_Payload = Base64.getUrlEncoder().encodeToString(parsedJWT_Payload.getBytes());


       // Create JWT_Signature, then encode

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

sha256_HMAC.init(new SecretKeySpec(JWT_SecretKey.getBytes(), "HmacSHA256"));

byte[] signature = sha256_HMAC.doFinal((encodedJWT_header + '.' + encodedJWT_Payload).getBytes());

       String encodedJWT_Signature = Base64.getUrlEncoder().encodeToString(signature);


       // Create token and store as property in virtual service runtime

       String JWT_Token = encodedJWT_header + '.' + encodedJWT_Payload + '.' + encodedJWT_Signature;


Additional Information

To Decode :