JWT Token - Client Side Generation

We are already aware of using the REST API with different authentication methods like OAuth 2.0, API keys, and so on. In this article, we are going to discuss JWT Token Authentication, wherein we will create a JWT Token inside the Studio using JS Code Block, and using this generated token, access resources from a REST API.

REST API Connector Configuration

  1. Set the Authentication to None
  2. Add a new header Authorization which will take the JWT Token as input

App Builder

For this use case, we will use the Screen Open Action to trigger data retrieval from the REST API. To display the data accessed from the REST API, we are using the TableGrid Control.


 

We first add a JS Code Block and write the JWT Token creation logic in it.

Code

function base64url(source) {
    encodedSource = CryptoJS.enc.Base64.stringify(source);
    encodedSource = encodedSource.replace(/=+$/, '');
    encodedSource = encodedSource.replace(/\+/g, '-');
    encodedSource = encodedSource.replace(/\//g, '_');
    return encodedSource;
}

function createJWT(header, data, secret = undefined) {
    let stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
    let encodedHeader = base64url(stringifiedHeader);
    let stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
    let encodedData = base64url(stringifiedData);
    let token = encodedHeader + "." + encodedData;
    if (!secret) return token;
    let signature = CryptoJS.HmacSHA256(token, secret);
    signature = base64url(signature);
    return encodedHeader + "." + encodedData + "." + signature;
}

const header = {
    "alg": "HS256",
    "typ": "JWT"
};
const data = {
    "email": "john@example.com",
    "password": "@johncarter"
};
const secret = "john@99";

const token = createJWT(header, data, secret);
output = `Bearer ${token}`;

Code Explanation

The function createJWT accepts three parameters.:

  • header: header of the JWT token in JSON format
  • data: payload of the JWT token in JSON format
  • secret: this is optional, it accepts a string format which is used to sign the JWT if supplied
     

Capture the output of the JS Code Block into a variable to pass it to the REST API Connector, in our case the variable is authToken.


 

Now add the REST API Connector we created earlier, and in the field of Authorization select the JS Code Block output.


 

Add a variable which will hold the response sent by the REST API, in our case the variable is data.


 

Now the only thing left is to bind the response data received from the REST API to TableGrid Control, so add the Set Control Value Action to the REST API’s success branch.


 

Run the App and you will see that the API data is automatically loaded onto the TableGrid.