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
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:
The token is returned as a cookie, do you need to add it to the header?