How to send nextauth CSRF + callbackUrl cookies from getServerSideProps properly ? #3588
Unanswered
ComicScrip
asked this question in
Help
Replies: 2 comments 4 replies
-
While I do agree, and I can confirm, that your method works, 👍 I'm curious, why would you want to use a JS framework, and at the same time try to make it work without JavaScript. |
Beta Was this translation helpful? Give feedback.
1 reply
-
For session, there's a method called |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Question 💬
I followed what is written in the docs to setup a simple credentials authentication with a custom signin page :
pages/api/auth/[...nextauth].js
pages/login.js
This implementation does not work when the user's browser visits the
/login
page for the first time and tries to authenticate with correct credentials, because although the CSRF token to put in the login form is set, the corresponding CSRF cookie is not.So the first login attempt will fail, but will set the required cookie in the browser and then the second attempt will succeed because this time we have the cookie along with the CSRF form token.
To make the first attempt with correct credentials succeed, CSRF cookie should be set before validating the user's credentials in
authorize
.A partial solution is written in the docs, calling
signIn
in the custom signin page instead of relying on the default form submission will handle the CSRF token :The problem is that it works only when JS is enabled in the browser, because
signIn
rely on client side JS.To make it work without client side JS enabled, I found a solution : Instead of calling
signIn
, I just send the CSRF cookies ingetServerSideProps
by adding headers to the response :So finally, my questions :
getCsrfTokenAndSetCookies
to the official NextAuth's API ?How to reproduce ☕️
Here's a PR to show the fix I implemented : https://github.com/ComicScrip/nextauth-csrf-cookie-issue/pull/1/files
To test :
npm i && npm run dev
http://localhost:3000/login
directly (don't navigate to that page using the signin button on the homepage)npm run dev
http://localhost:3000/login
directly (don't navigate to that page using the signin button on the homepage)Contributing 🙌🏽
Yes, I am willing to help answer this question in a PR
Beta Was this translation helpful? Give feedback.
All reactions