首页 > 解决方案 > 在 Cypress 中存储访问令牌 - Cypress OAuth 2.0

问题描述

对于我的应用程序,我尝试通过 API 而不是 UI 登录

我需要存储 accessToken 以浏览应用程序

我当前的登录方法如下所示

 Cypress.Commands.add('login', (overrides = {}) => {
  Cypress.log({
    name: 'loginViaAuth0',
  });

  const options = {
    method: 'POST',
    url: Cypress.env('auth_url'),
      headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
      username: Cypress.env('auth_username'),
      password: Cypress.env('auth_password'),
    }
  }

  cy.request(options);
});

我需要将 accessToken 存储到资源文件中。我已经尝试了各种方法,例如这里,但没有成功

在 Cypress 中设置本地存储

谢谢

编辑:

我已经尝试过了,但仍然没有运气

 Cypress.Commands.add('login', (overrides = {}) => {
  cy.request({
    method: 'POST',
    url: Cypress.env('auth_url'),
    body: {
      user: {
        email: Cypress.env('auth_username'),
        password: Cypress.env('auth_password'),
      }
    }
  })
    .its('token')
    .then((token) => {
      window.localStorage.setItem('accessToken', token);
    });
});

编辑:这最终对任何感兴趣的人都有效

Cypress.Commands.add('login', (overrides = {}) => {
cy.request({ 
    method: 'POST', 
    url: Cypress.env('auth_url'), form: true, 
    body: { grant_type: 'client_credentials', scope: 'xero_all-apis' ,
           username: Cypress.env('auth_username'), 
           password: Cypress.env('auth_password'), } }) 
    .its('body') 
   .then(res => { 
     cy.setLocalStorage('accessToken',res.accessToken);
   }); 
});

标签: typescriptoauth-2.0cypress

解决方案


@Steven983,请试试这个

Cypress code Cypress.Commands.add('login', () => { 
cy.request({ 
    method: 'POST', 
    url: Cypress.env('auth_url'), form: true, 
    body: { grant_type: 'client_credentials', scope: 'xero_all-apis' }, 
    auth: { 
           username: Cypress.env('auth_username'), 
           password: Cypress.env('auth_password'), } }) 
    .its('body') 
   .then(res => { 
     cy.log(res.body.accessToken) //To verify token is shown in console
     cy.setLocalStorage('accessToken', res.body.accessToken); 
   }); 

});


推荐阅读