The token automatically and what to check
A login post-response script saves the token to a variable used as Bearer {{token}}, and a pre-request script refreshes it before expiry. Mandatory checks: no token, a broken and an expired token give 401, someone else's resource gives 403 or 404, and an ordinary user on an admin endpoint gives 403. For BOLA/IDOR two users are used, checking both the status and the absence of the owner's data in the body.
API · Authorization
The token lives 15 minutes, the collection runs an hour. How to avoid pasting it by hand?
A regression run of 60 requests. The first 20 pass, then 401s begin: the token pasted in the morning expired halfway. Refreshing the token by hand before every run is a source of unstable runs and lost time. The token must be obtained automatically, and along with it we check that authorization behaves correctly when there is no token, when it is broken or when it belongs to someone else.
Below: how to save the token after login, how to refresh it when it expires, and which set of checks is mandatory.
How the token gets into requests automatically
Postman runs scripts before and after a request. In the post-response script of the login the token is saved to an environment variable, and the collection is set to Bearer {{token}}.
// Tests tab of POST {{baseUrl}}/auth/login (post-response script)
pm.test('login: 200', () => pm.response.to.have.status(200));
const { accessToken, expiresIn } = pm.response.json();
pm.expect(accessToken, 'accessToken').to.be.a('string');
pm.environment.set('token', accessToken);
pm.environment.set('tokenExpiresAt', Date.now() + expiresIn * 1000);
The chain from login to requests
Why it is designed this way. An environment variable is shared state between the requests of a collection: the write script runs once, and the {{token}} substitution happens on every send. The token lives in a variable, not in a request, so it changes in one place. The order matters here: in Runner and Newman login must be the first request, because the following ones read the variable it writes.
Example: a token that expires in the middle of a run
Before: login once at the start, but the collection runs longer than the token lives, so the middle fails with 401. After: before each request we check the expiry time and, if needed, get a new token. This is the collection pre-request script:
// Collection > Pre-request Script: refresh the token when it is near expiry
const expiresAt = Number(pm.environment.get('tokenExpiresAt') || 0);
if (Date.now() > expiresAt - 30000) {
pm.sendRequest(
{
url: pm.environment.get('baseUrl') + '/auth/login',
method: 'POST',
header: { 'Content-Type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({
login: pm.environment.get('login'),
password: pm.environment.get('password'),
}),
},
},
(err, res) => {
if (err) throw err;
const { accessToken, expiresIn } = res.json();
pm.environment.set('token', accessToken);
pm.environment.set('tokenExpiresAt', Date.now() + expiresIn * 1000);
},
);
}
The 30-second margin is needed so the token does not expire while the request is in flight. The login and the password come from environment variables, not from the script text. A script like this sends the extra request only when the token is really old, so the collection does not get slower without need. Note that pm.sendRequest is asynchronous, and the main request waits for the script to finish.
What to check in authorization
- No token: 401, not 200 and not 500.
- A broken and an expired token: 401, with no details about the reason in the body.
- A token after logout: 401 if the contract promises invalidation; otherwise the policy is recorded.
- Someone else's resource: user B's token on a resource of A gives 403 or 404, but never data.
- Role rights: an ordinary user on an admin endpoint gives 403.
The last two points are BOLA/IDOR, one of the most dangerous defects in fintech. Two test users are needed: create a resource as the first and request it with the token of the second. The same in code, with tokens obtained once per worker:
import { test as base, expect, request as pw } from '@playwright/test';
async function login(user: string) {
const ctx = await pw.newContext({ baseURL: process.env.API_URL });
const res = await ctx.post('/auth/login', {
data: { login: user, password: process.env.TEST_PASSWORD },
});
const { accessToken } = await res.json();
await ctx.dispose();
return accessToken as string;
}
const test = base.extend<{}, { tokenA: string; tokenB: string }>({
tokenA: [async ({}, use) => use(await login('user-a')), { scope: 'worker' }],
tokenB: [async ({}, use) => use(await login('user-b')), { scope: 'worker' }],
});
test('user B cannot read the transfer of user A', async ({ request, tokenA, tokenB }) => {
const created = await request.post('/v1/transfers', {
headers: { Authorization: 'Bearer ' + tokenA },
data: { toAccount: 'UA21...', amount: 10, currency: 'UAH' },
});
const { id } = await created.json();
const res = await request.get('/v1/transfers/' + id, {
headers: { Authorization: 'Bearer ' + tokenB },
});
expect([403, 404]).toContain(res.status());
expect(await res.text()).not.toContain('UA21');
});
The test checks two assumptions: the status is not 200, and there is no owner data in the body (a check by a fragment of the account number). The status alone is not enough: a server can return 403 with the full object in the body.
Limits and alternatives
- A script that logs in before every request without checking the expiry overloads the login service and can hit a rate limit. Refresh only when needed.
- For OAuth 2.0 Postman can obtain and refresh the token itself (Get New Access Token, auto-refresh). For a simple login on your own endpoint, scripts are handier.
- In Newman environment variables are not kept between runs, so the token is obtained within a run.
- In Playwright the analogue is a worker-scoped fixture or a setup project that logs in once and shares the state. The approach is the same: the token in one place, tests do not know about it.
Common mistakes
- Not checking the login status in the script. If login failed,
undefinedis written to the variable and the next 59 requests give 401 with no clear reason. - One test user for everything. Checking someone else's access is impossible, and IDOR goes unnoticed.
- Checking only the status of foreign access. A 403 with data in the body is the same leak.
- Login and password in the script text or the collection. They end up in the repository and in logs. They are kept in environment variables or CI secrets.
Check yourself
A collection run fails with 401 at request 21 while everything was fine at the start. What is the likeliest cause and the fix?
Answer
The token expired in the middle of the run: it was obtained once, and the collection is longer than its lifetime. Add a pre-request script that refreshes the token when less than a margin is left, or run the collection in shorter parts.
A GET of someone else's account with another user's token returns 403, but the body contains the full account JSON. Did the test pass?
Answer
No. The status is right, but the data leaked, so this is BOLA/IDOR with a wrong status. Both the code and the absence of owner data in the body are checked.
pm.environment.set and use {{token}} on the collection. I check 401 with no token, with a broken one, an expired one and after logout. Middle/Senior: I refresh the token in a pre-request script when less than a margin is left, not before every request. For IDOR I take two users: I create a resource as the first and read it with the token of the second, checking both the status and the absence of data in the body. I keep the login and password in environment variables, not in the collection.