Emy Iacob
Emy Iacob

Reputation: 11

Bearer auth token stored in localstorage passed in multiple API calls (Cypress)

I'm trying to use the bearer auth token received from a Cypress command in some tests but I'm getting an error Cypress error

Here is my command code:

Cypress.Commands.add("getToken", () => { 


    
cy.request({

    method: 'POST',
    url: 'https://login.microsoftonline.com/abcc1234-abc12345-abcc1234-abc12345/oauth2/v2.0/token',
    form: true,
    body: {
        'client_id': 'abcc1234-abc12345-abcc1234-abc12345abcc1234-abc12345/'
        'client_secret' : 'J2Kq.XXXXXXXX.Xt_-XXXXXX',
        'grant_type': 'client_credentials'
       
    }
    
})
.then((response) =>{
    const tokenAuth = response.body.access_token;
    
    window.localStorage.setItem('auth', tokenAuth);

And here is my test:

describe('API Testing', ()=>{
    beforeEach(() => {
        cy.getToken()
        
    })
    it('Connector - GET', () =>{
        let a = "Bearer " + localStorage.getItem('auth')
        cy.log(a);
        cy.request({
            method:'GET',
            url:'https://XXXX-XXXXX-XXXXXXXXX.azurewebsites.net/api/v1/connectors/cost-max-and-power-intervals',
            auth : 'a'

            
        })
            
            .then((response) =>{
        expect(response).to.have.property('status', 200)
        expect(response.body).to.not.be.null
        expect(response.body).to.have.property('costMax', 35)
    })

 })

I've also tried to set a header in request but without luck. :(

Thank you in advance!

Upvotes: 0

Views: 394

Answers (1)

Emy Iacob
Emy Iacob

Reputation: 11

Looks like I've made a confusion, auth is not the same with Autorization. I managed to make it work by replacing auth with Autorization : a

Upvotes: 1

Related Questions