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.