'Cypress - Status: 401 - Unauthorized in token authentication to other API call

I would like to ask for your help regarding the authentication token to be used in other API calls. Below are the scripts of the command and test case:

//command.js
import "cypress-localstorage-commands";
Cypress.Commands.add('login', () => { 
cy.request({
  method: 'POST',
  url: Cypress.env('api_auth'),
  body: {
    email: Cypress.env('email'),
    password: Cypress.env('password'),
 }
 })
 .its('body')
 .then(body => {
  cy.window().then(win => win.localStorage.setItem('jwt', body.token))
 })

//test case
describe('GET Data', ()=> {
before(() => {
    cy.login();
    cy.saveLocalStorage();
  });
  
  beforeEach(() => {
    cy.restoreLocalStorage();
  });

it('GET - View All Data', () =>{
    cy.request({
        method : 'GET',
        url : Cypress.env('api_data'),
    }).then((res) =>{
        expect(res.status).equal(200)
    })
})


Solution 1:[1]

In my approach i have the same command, but instead of storing the token in the local storage, I'm adding it to the cypress.env file in the object of the admin, because i have several admins so my object file goes like so

{
admins: 
admin1:{
"username":"admin1",
"password": "123456",
"token":""
},
admin2:{
"username":"admin1", 
"password": "123456",
"token":""
 }
} 

This way you can store several admins/user tokens and just attach as:

Cypress.env.admins.admin1.token or Cypress.env.admins.admin2.token

I think this approach is simpler and in about 300 tests i've seen no problems regarding speed of the test execution or anything other

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bogdan Pehlivanov