Transferring bearer token from API request to other tests using Cypress

Viewed 1256

I am running tests on a web application to test WYSIWYG functionality and XSS vulnerabilities. I use the following command before

beforeEACH(() => {
       cy.vaderAuth()
    });

Cypress.Commands.add('vaderAuth', () => {
  let config = Cypress.config();

  cy.request({
    method: 'POST',
    url: Cypress.config('tokenUrl') + '/api/v1?actions=api/v1/login',
    body: {
      username: config.horizon.username,
      password: config.horizon.password,
    }
  }).then(response => {
    window.localStorage.setItem('JWT', response.body['api/v1/login'].token)
  })
})

The above command successfully gets the Bearer Token but then the following test throws a 401 Unauthorised error.

it('Sending a regular API request to Welcome Messages', function() { 
        cy.request({
            method : 'POST',
            url : '/api/v1/organisations/welcome-message?actions=api/v1/organisations/welcome-message/set-welcome-messages',
            body : {"welcome_messages":[{"message":"<p>Test investor welcome message!</p>","type":"User"},{"message":"<p>Internal User welcome message Cypress Test. </p>","type":"Internal User"},{"message":"<p>Test entrepreneur welcome message!</p>","type":"Entrepreneur"}]},
            headers : {"Authorization": "Bearer " + window.localStorage.JWT}
    })
})

beforeEach working, API request 401

401 cypress error

I have checked the failure and it is sending the Bearer Token as a header, and the request headers match the headers the same request sends if I enter the Bearer Token manually as follows.

  it('Sending a regular API request to Welcome Messages', function() { 
        cy.request({
            method : 'POST',
            url : '/api/v1/organisations/welcome-message?actions=api/v1/organisations/welcome-message/set-welcome-messages',
            body : {"welcome_messages":[{"message":"<p>Test investor welcome message!</p>","type":"User"},{"message":"<p>Internal User welcome message Cypress Test. </p>","type":"Internal User"},{"message":"<p>Test entrepreneur welcome message!</p>","type":"Entrepreneur"}]},
            //headers : {"Authorization": "Bearer (insertbearertokenhere)}
            
    })
})

When entering the Bearer Token manually the following tests all run smoothly with no error, but if I have to go in and change the Bearer Token every time I run these tests, it kind of defeats the point of automating it as by the time I've logged into my web app and got the token, I may as well test the application manually.

Any help on this would be greatly appreciated as I have been working on it with no luck for around a week now.

0 Answers
Related