JWT in Apex | What is JWT Token? | How to use JWT Token?

JWT in Apex | What is JWT Token? | How to use JWT Token?

JWT in Apex | What is JWT Token? | How to use JWT Token?

 

 

JWT in Apex | What is JWT Token
 
 

 

 

 

Content table:-

  1. What is JWT
  1. JWT structure
  1. JWT creation example in Apex

 

What is JWT?

JSON Web Token (JWT) and JWT in Apex | What is JWT Token? | How to use JWT Token? is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

These tokens offer a method to establish secure server-to-server authentication by transferring a compact JSON object with a signed payload of your account’s API Key and Secret. For more information about JSON Web Tokens check jwt.io.

 

Token JWT in Apex

 

 

JWT structure

When we talk about JSON Web Token, it is consist of 3 parts.

  1. Header
  1. Payload
  1. Signature

Header

Which contains the algorithm and type which will be used to sign the request

Property alg defines which signing algorithm is being used.

Property typ defines the type of token and it is always JWT.

Then, this JSON is Base64Url encoded to form the first part of the JWT.

{
    "alg": "HS256",
    "typ": "JWT"
}

Payload

The second part of the token is the payload, which contains the claims or the pieces of information being passed about the user and any metadata required. It is mandatory to specify the following claims and others:

  • issuer (iss): Your API key
  • subject (sub): Workspace identifier
  • expiration time (exp): Timestamp (Unix epoch time) until the token is valid. It is highly recommended to set the exptimestamp for a short period. if a token is intercepted or shared, the token will only be valid for a short period of time.
  • The payload is then Base64Url encoded to form the second part of the JSON Web Token.
{
    "iss": "ad54aaff89ffdfeff178bb8a8f359b29fcb20edb56250b9f584aa2cb0162ed4a",
    "sub": "testsalesforce@gmail.com",
    "exp": 1586112639
}

Signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload) , secret)

Putting all together with “.” notation.

JWT Token = (encoded Header) + '.' + (encoded Payload) + '.' + (encoded Signature)

JWT creation example in Apex

public static string JWTCreationController(){
        // API key and username(sub) come from Custom setting.
        PDFGeneratorSettings__c pGen = PDFGeneratorSettings__c.getOrgDefaults();
        // Genrate expiration time in miliseconds
        Long expTime = Long.valueOf(String.valueOf(DateTime.now().getTime()).subString(0,10));
        String header = '{"alg": "HS256","typ": "JWT"}';
        String payload = '{"iss":'+pGen.APIKey__c+',"sub":'+pGen.Username__c+',"exp":'+expTime+'}';
        String secret = pGen.SecretKey__c;
        // Encode the header in base64Encode
        String encodedHeader = EncodingUtil.base64Encode(Blob.valueOf(header)).replaceAll('\\+', '-').replaceAll('/', '_').replaceAll('=', '');
        System.debug('encodedHeader:: '+encodedHeader);
        // Encode the payload in base64Encode
        String encodedPayload = EncodingUtil.base64Encode(Blob.valueOf(payload)).replaceAll('\\+', '-').replaceAll('/', '_').replaceAll('=', '');
        System.debug('encodedPayload:: '+encodedPayload);
        String signatureInput = encodedHeader + '.' + encodedPayload;
        // Genrate digital signature
        Blob signature = Crypto.generateMac('hmacSHA256', Blob.valueOf(signatureInput), Blob.valueOf(secret));
        String encodedSignature = EncodingUtil.base64Encode(signature).replaceAll('\\+', '-').replaceAll('/', '_').replaceAll('=', '');
        System.debug('encodedSignature:: '+encodedSignature);
        // JWT(JSON WEB TOKEN)
        String jwt = encodedHeader + '.' + encodedPayload + '.' + encodedSignature;
        System.debug('jwt:: '+jwt);
        return jwt;
    }

This Apex code generates a JWT token using the HMAC SHA256 algorithm. It takes in the API key and secret key from a custom setting called PDFGeneratorSettings__c, and generates the iss and sub claims using the APIKey__c and Username__c fields from the custom setting, as well as the current Unix epoch time for the exp claim. The resulting JWT is returned as a string.

Result

JWT Token :- eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhZDU0YWFmZjg5ZmZkZmVmZjE3OGJiOGE4ZjM1OWIyOWZjYjIwZWRiNTYyNTBiOWY1ODRhYTJjYjAxNjJlZDRhIiwic3ViIjoidGVzdHNhbGVzZm9yY2VAZ21haWwuY29tIiwiZXhwIjoxNTg2MTEyNjM5fQ.-t94I7YW-j1_b0VrjvIC85Ih8v6uiXe_yrsvGUnAyZU

References

  1. Change header & payload into base64Encode use EncodingUtil Class in Apex.
  1. Create signature use Crypto Class in Apex.
  1. Genrating expiration time use DateTime Class in Apex