Skip to content

How To Use Jwt In Postman

API Testing Blog

Using JWT in Postman for API Testing

JSON Web Tokens (JWTs) are a popular standard for securely transmitting information between parties. They are often used for authentication and authorization in APIs. Postman is a powerful tool for API testing, and it provides excellent support for working with JWTs.

1. Generating a JWT

Before testing an API that uses JWTs, you’ll need a valid token. There are several ways to generate a JWT:

  • Using an online JWT generator: Many websites offer free online JWT generators. These tools let you specify the token’s claims and generate a JWT in a few clicks. Here are some options:

  • Writing your own code: If you need more flexibility, you can write your own code to generate JWTs. Libraries are available in most programming languages to handle this task.

2. Understanding JWT Structure

A JWT consists of three parts, separated by dots (.):

  • Header: Contains information about the token, including the algorithm used to sign the token (alg) and the token type (typ).
  • Payload: Contains the actual data - claims - about the authenticated user, like username, roles, etc.
  • Signature: This is a hash of the header and payload, signed with a secret key. It ensures token integrity and authenticity.

3. Using Pre-request Scripts to Generate JWTs

Postman’s pre-request scripts allow you to automate actions before sending a request. You can use them to generate a JWT dynamically:

Example: Assuming you are using the jsonwebtoken library in Node.js:

// Get the secret key from your environment variable.
const secretKey = pm.environment.get('JWT_SECRET_KEY');
// Create the payload for the JWT.
const payload = {
"iss": "your-application",
"sub": "your-user-id",
"iat": Math.floor(Date.now() / 1000),
"exp": Math.floor(Date.now() / 1000) + (60 * 60) // Expire in one hour
};
// Generate the JWT.
const token = jwt.sign(payload, secretKey);
// Set the token in the request headers.
pm.environment.set("Authorization", "Bearer " + token);

Explanation:

  • The code obtains the JWT_SECRET_KEY from the Postman environment variable, which you would need to define beforehand.
  • It constructs a sample payload for the JWT, including iss (issuer), sub (subject), iat (issued at), and exp (expiration time).
  • It uses the jsonwebtoken library to generate the JWT.
  • Finally, the script sets the generated token as an Authorization header value in the request.

4. Adding the JWT to Request Headers

Once you have a JWT, you need to send it with your requests to the API. Postman allows you to add headers dynamically:

Example:

  1. Open the request you want to send.
  2. In the Headers tab, click the Add button.
  3. Enter Authorization in the Key field and Bearer [your JWT] in the Value field.

Important: Replace [your JWT] with the actual JWT you generated in the previous steps.

5. Managing JWTs in the Postman Environment

For automated API testing, storing JWTs in a Postman environment is helpful:

Example:

  1. In Postman, navigate to the environment and click Add to create a new variable.
  2. Set the Key as JWT_TOKEN or any suitable name.
  3. In the Value field, paste your JWT.

This way, you can access the JWT in your pre-request scripts using pm.environment.get("JWT_TOKEN").

6. Using the JWT token in the tests

Now that you have integrated your JWT into the API request, you can start testing your API endpoints. Postman’s test scripts give you a way to validate the response and check if the JWT has been successfully verified by your API backend.

Example:

pm.test("Response contains expected data", function() {
const jsonData = pm.response.json();
pm.expect(jsonData.success).to.be.true;
});
pm.test("Status code is 200", function() {
pm.expect(pm.response.code).to.be.equal(200);
});

In addition to verifying expected data, you can also test whether specific claims were included in the received JWT’s payload. To do this, you need to decode the JWT from the response’s headers.

Example:

const jwt = require('jsonwebtoken');
// Extract the JWT from the Authorization header
const authHeader = pm.response.headers.get('Authorization');
const token = authHeader.split(' ')[1];
// Decode the JWT
const decoded = jwt.decode(token);
// Verify the user ID
pm.test("JWT payload contains the correct user ID", function () {
pm.expect(decoded.sub).to.be.equal("your-user-id");
});
// Verify the role
pm.test("JWT payload contains the correct role", function () {
pm.expect(decoded.role).to.be.equal("administrator");
});

7. Testing with Invalid or Expired JWTs

Testing with invalid or expired JWTs helps assess the API’s security and error handling:

Example:

  1. Invalid JWT: Modify the JWT by changing the signature or payload and observe the API’s response. This should result in an error indicating an invalid token.
  2. Expired JWT: Generate a JWT with an expiration time that has passed. Send this token to the API to test its response and ensure that it properly handles expired tokens.

Testing these scenarios helps you assess the robustness of your API’s authentication mechanism.

Conclusion

By following this guide, you can successfully integrate JWTs into your API testing workflow using Postman. You’ll be able to generate, send, verify, and test JWTs efficiently, enhancing the confidence in your API’s security and functionality. Remember to adapt these examples to your specific API and test scenarios.

API Testing Blog