使用赛普拉斯将承载令牌从API请求传输到其他测试

时间:2020-07-23 08:37:14

标签: jwt authorization cypress bearer-token

我正在Web应用程序上运行测试,以测试所见即所得的功能和XSS漏洞。我之前使用以下命令

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)
  })
})

上面的命令成功获取了Bearer令牌,但随后的测试引发了401未经授权的错误。

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

我已经检查了失败,并且它正在将Bearer Token作为标头发送,并且如果我按如下所示手动输入Bearer Token,则请求标头与相同请求发送的标头匹配。

  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)}
            
    })
})

当手动输入Bearer Token时,以下测试均可以顺利运行且没有错误,但是,如果我必须每次运行这些测试时都必须进行更改并更改Bearer Token,则可能会失去自动化它的意义。当我登录到Web应用程序并获得令牌时,最好还是手动测试该应用程序。

对此的任何帮助将不胜感激,因为我一直在努力工作了大约一个星期。

0 个答案:

没有答案