How do you organise authorisation in API tests?
API test login goes into one command, and credentials come from environment variables, not from code. In a token scheme the test passes the token itself in the Authorization header, while in a cookie scheme cy.request stores Set-Cookie in the browser and sends it with later requests. The password is hidden with log: false, and the result is cached with cy.session. Besides 200, 401 and 403 are checked.
Cypress · API testing
A test user’s password sits in the spec and shows up in the CI video. How do you organise login in API tests properly?
Most APIs need authentication, so the same block appears in every test: login, token, header. If you copy it, changing the login endpoint breaks dozens of files, and a password in code lands in the repository. So login goes into one command, credentials come from environment variables, and what to pass on (a token or a cookie) depends on how the server works.
How it works and why
There are two typical mechanisms. In a token scheme login returns a JWT or another token in the body, and the client sends it in an Authorization: Bearer … header. Cypress remembers nothing, so the test passes the token by hand. In a cookie scheme the server answers with Set-Cookie and cy.request saves it in the browser and adds it to later requests. No header is needed then, and cy.visit gets a logged-in user at once. To avoid logging in in every test, the result is cached through cy.session (a separate lesson).
Two authentication schemes
Authorization: Bearer …
Login returns the token in the body. The test puts it into every request itself. Cypress remembers nothing.
Set-Cookie
cy.request saves the cookie in the browser and sends it on by itself, including to cy.visit. No header needed.
Example: a custom command and three access scenarios
The command reads credentials through cy.env() (Cypress.env() was removed in Cypress 16) and returns the token. The log: false option hides the request with the password from the Command Log:
// cypress/support/commands.ts
Cypress.Commands.add('apiLogin', (role = 'USER') => {
return cy
.env([role + '_EMAIL', role + '_PASSWORD'])
.then((creds) =>
cy.request({
method: 'POST',
url: '/api/auth/login',
body: { email: creds[role + '_EMAIL'], password: creds[role + '_PASSWORD'] },
log: false, // the password stays out of the Command Log and the video
}),
)
.its('body.token');
});
// cypress/support/index.d.ts
declare global {
namespace Cypress {
interface Chainable {
apiLogin(role?: string): Chainable<string>;
}
}
}
export {};
Now the tests. For a token in a header Cypress has a handy auth: { bearer } option. Besides the positive scenario we check what breaks most often: a damaged token and a role without rights.
describe('API: orders', () => {
let token: string;
before(() => {
cy.apiLogin().then((t) => { token = t; });
});
it('200 with a token', () => {
cy.request({ url: '/api/orders', auth: { bearer: token } })
.its('status').should('eq', 200);
});
it('401 with a damaged token', () => {
cy.request({ url: '/api/orders', auth: { bearer: token + 'x' }, failOnStatusCode: false })
.its('status').should('eq', 401);
});
it('403 for a role without rights', () => {
cy.apiLogin('GUEST').then((guest) => {
cy.request({ url: '/api/admin', auth: { bearer: guest }, failOnStatusCode: false })
.its('status').should('eq', 403);
});
});
});
The token is received once in before and kept in a module variable, not in Cypress variables. The three cases check different things: 200 proves access works, 401 that the server really validates the token, 403 that access levels differ. A test that checks only 200 will not notice broken authorisation.
Limits and alternatives
Credentials do not belong in code or the repository: in CI they come from secrets, locally from uncommitted files. A separate user per role is easier to maintain than one “admin for everything”. A token has a lifetime, so a long suite may hit an expired token: for such cases there is a re-login before the run or a lifetime check. Under OAuth or SSO a direct login by request is sometimes impossible, and then a test-only sign-in is agreed. In Playwright such a context is created once through playwright.request.newContext with extraHTTPHeaders and handed out through a fixture.
Typical mistakes
- A password in code or in a committed
cypress.config: it lands in the repository. - Logging in in every test instead of once: extra requests and a slow suite.
- Checking only 200 and not 401 and 403.
- Putting a token into a header when the server uses cookies: the test passes by accident.
- Leaving
log: trueon the request with a password: it ends up in the Command Log and the video.
Check yourself
How does passing authorisation differ in a token scheme and a cookie scheme in Cypress?
Answer
The test puts a token into a header itself, for example through auth: { bearer }. cy.request saves a cookie in the browser and adds it to later requests automatically.
Besides 200 for a logged-in user, which two negative access scenarios are worth checking?
Answer
401 with no token or a damaged token (the server checks authentication) and 403 for a user without the needed role (the server distinguishes rights).