Hi Anand,
I am making the assumption that you already have a virtual service configured with the JSON DPH. So, you would have inside the virtual service an incoming request with 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 I would also create 2 properties in your config file:
- "JWT_Header"= { "typ": "JWT", "alg": "HS256" }
- "JWT_Payload"= { "subscriptionAccountNumber": "1234567", "status": "ACTIVE", "userEmail": "{{request_username}}", "name": "John Doe", "subscriptionId": "001" }
And you will also have to make your secret key available, so my assumption below is you also provided it in your 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;
testExec.setStateValue("JWT_Token", JWT_Token);
Unfortunately, the above script is not tested
Cheers,
Danny