Token-based authentication in Cypress - Build an Automation Script
describe('Token-based authentication test', () => { it('logs in and accesses protected profile using token', () => { // Step 1: Login and get token cy.request({ method: 'POST', url: '/api/login', body: { username: 'testuser', password: 'TestPass123' } }).then((loginResponse) => { // Assert login success expect(loginResponse.status).to.equal(200); expect(loginResponse.body).to.have.property('token').and.to.be.a('string').and.not.be.empty; const token = loginResponse.body.token; // Step 2: Use token to access protected profile cy.request({ method: 'GET', url: '/api/profile', headers: { Authorization: `Bearer ${token}` } }).then((profileResponse) => { // Assert profile access success expect(profileResponse.status).to.equal(200); expect(profileResponse.body).to.have.property('username', 'testuser'); expect(profileResponse.body).to.have.property('email').and.to.be.a('string').and.not.be.empty; }); }); }); });
This test uses cy.request() to send API calls directly without UI interaction.
First, it sends a POST request to /api/login with username and password. It asserts the response status is 200 and that the response body contains a non-empty token string.
Then, it stores the token in a variable and uses it in the Authorization header to send a GET request to /api/profile. It asserts the profile response status is 200 and checks that expected user data fields like username and email are present and valid.
This approach ensures the token is dynamically retrieved and used, following best practices for token-based authentication testing.
Now add data-driven testing with 3 different sets of valid username and password combinations to verify token-based authentication works for multiple users.
Practice
Solution
Step 1: Understand token-based authentication purpose
Token-based authentication lets tests bypass UI login by using tokens directly.Step 2: Compare options
Only It allows tests to log in quickly without interacting with the UI. correctly states the advantage of faster login without UI interaction.Final Answer:
It allows tests to log in quickly without interacting with the UI. -> Option DQuick Check:
Token-based authentication = Fast login without UI [OK]
- Thinking token auth requires UI interaction
- Confusing token auth with disabling APIs
- Assuming token auth auto-generates UI
Solution
Step 1: Identify command for API calls
cy.request() is used to make HTTP requests to APIs, including login endpoints.Step 2: Eliminate other commands
cy.visit() loads pages, cy.get() selects DOM elements, cy.contains() finds text; none request tokens.Final Answer:
cy.request() -> Option CQuick Check:
API token request = cy.request() [OK]
- Using cy.visit() to get tokens
- Confusing cy.get() with API calls
- Trying cy.contains() for authentication
token after the test runs?
let token = '';
cy.request('POST', '/api/login', { username: 'user', password: 'pass' })
.then((response) => {
token = response.body.token;
});Solution
Step 1: Understand asynchronous assignment
The token variable is assigned inside the .then() callback after the API response arrives.Step 2: Confirm token value after request
response.body.token contains the token string from the API, so token gets that value.Final Answer:
The token string returned by the API in response.body.token -> Option BQuick Check:
token = response.body.token string [OK]
- Assuming token stays empty due to async
- Thinking token is undefined without checking API
- Confusing token with full response object
cy.request('POST', '/api/login', { username: 'user', password: 'pass' })
.then((response) => {
cy.setCookie('authToken', response.token);
});Solution
Step 1: Check response object structure
The token is usually inside response.body.token, not directly response.token.Step 2: Validate cy.setCookie usage
cy.setCookie is a valid command to set cookies in Cypress.Final Answer:
response.token should be response.body.token to access the token -> Option AQuick Check:
Access token via response.body.token [OK]
- Using response.token instead of response.body.token
- Thinking cy.setCookie is invalid
- Changing POST to GET incorrectly
A) cy.request('POST', '/api/login', {username: 'user', password: 'pass'}).then(res => {
cy.setCookie('token', res.token);
});
cy.visit('/protected');
B) cy.visit('/protected');
cy.request('POST', '/api/login', {username: 'user', password: 'pass'}).then(res => {
cy.setCookie('token', res.body.token);
});
C) cy.request('POST', '/api/login', {username: 'user', password: 'pass'}).then(res => {
cy.setCookie('token', res.body.token);
cy.visit('/protected');
});
D) cy.setCookie('token', 'dummy');
cy.visit('/protected');Solution
Step 1: Understand asynchronous flow
Token must be set before visiting the protected page, so visit must happen after setting cookie inside .then().Step 2: Analyze options
Request token, set cookie, then visit protected page inside .then() callback sets cookie and visits page inside .then(), ensuring correct order and token availability.Final Answer:
Request token, set cookie, then visit protected page inside .then() callback -> Option AQuick Check:
Set token cookie before visiting page inside .then() [OK]
- Visiting page before setting token cookie
- Setting cookie outside async callback
- Using dummy tokens without real login
Ready to prove it?
Pass the test and this pattern moves unknown
