skip to Main Content

I’m trying to build a direct API login using cypress. The app I want to test uses nextAuthJS (REST docs)

With postman I checked successfully the login POST request with this body as x-www-form-urlencoded:

username: 'user'
password: 'pass'
csrfToken: token // <= I recieved the token from `/api/auth/csrf` as a simple GET request.

And this is working, as next-auth.session-token cookie is created.

Now in my cypress test I tried to build up the same thing:

cy.request('/api/auth/csrf').then(({ body: { csrfToken } }) => {
  cy.request({
    method: 'POST',
    url: '/api/auth/callback/credentials',
    form: true,
    body: {
      username,
      password,
      csrfToken
    }
  }).then((res) => {
    cy.log(JSON.stringify(res))
  })
})

As you can see, I first do a GET request to recieve the csrf token. Then I use it in the post request, but I don’t get the session cookie in case of an successful login.

I’m not quite sure, if it is correct to use two nested then() and I don’t understand what I’m doing wrong as the postman request is working.

2

Answers


  1. Chosen as BEST ANSWER

    You have to check for the new created cookie instead for the request result.

    This is the working solution for an API login in cypress using nextAuthJS:

    cy.request('/api/auth/csrf').then(({ body: { csrfToken } }) => {
        cy.request({
          method: 'POST',
          url: '/api/auth/callback/credentials',
          form: true,
          body: {
            username,
            password,
            csrfToken
          }
        }).then(() => {
          cy.getCookie('next-auth.session-token').should('exist')
        })
    })
    

  2. The token is returned as a cookie, do you need to add it to the header?

    const username = 'user'
    const password = 'pass'
    
    cy.request('/api/auth/csrf')
    .then(({ body: { csrfToken } }) => {
    
       cy.request({
        method: 'POST',
        url: '/api/auth/callback/credentials',
        form: true,
        headers: {
          'Cookie': `sessionCookie=${csrfToken}`, 
          // or
          'Cookie': `X-CSRF-Token=${csrfToken}`
        },
        body: {
          username,
          password,
        }
      })
      .then((res) => {
        cy.log(JSON.stringify(res))
      })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search