Manage authentication token using Postman variables
Preconditions (2)
✅ Expected Result: The token is correctly saved in the environment variable and used in the Authorization header to access protected API successfully
Jump into concepts and practice - no test required
/* Login Request Tests */ pm.test('Login status code is 200', () => { pm.response.to.have.status(200); }); const jsonData = pm.response.json(); pm.test('Token is present in response', () => { pm.expect(jsonData.token).to.exist; }); pm.environment.set('authToken', jsonData.token); /* Protected API Request Tests */ pm.test('Protected API status code is 200', () => { pm.response.to.have.status(200); }); pm.test('Protected API response contains expected data', () => { const data = pm.response.json(); pm.expect(data).to.have.property('protectedData'); pm.expect(data.protectedData).to.be.a('string').that.is.not.empty; });
This script is split into two parts for two requests in Postman.
For the login request, it checks the status code is 200, then parses the JSON response to get the token. It asserts the token exists, then saves it to an environment variable authToken using pm.environment.set().
For the protected API request, it uses the saved authToken in the Authorization header as Bearer {{authToken}}. The tests verify the status code is 200 and the response contains the expected protected data property.
This approach ensures the token is dynamically managed and reused securely between requests.
Now add data-driven testing with 3 different user credentials to login and verify token management
let jsonData = pm.response.json();
pm.environment.set('authToken', jsonData.token);{{authToken}} in the next request if the response JSON is {"token": "abc123"}?let jsonData = pm.response.json();
pm.environment.set('token', jsonData.authToken);