4

I am trying to get my own authentication service working with my nextJS app. My own authentication service is a simple rest api that returns a JWT access token and a JWT refresh token on entering correct credentials.

Currently I am setting the JWT refresh token as a httpOnly cookie and the JWT access token into a state variable (in memory) in my nextjs app.

I am stuck at these points:

  • How do I pre-render sites in nextjs (getServerSideProps) with some custom user data that I want to fetch based on the JWT access token?

  • How can I pass this access token to getServerSideProps?

I wanted to pass the access token that is stored in memory to getServerSideProps but unfortunately I could not get it to work. Or at least I don't know how.

Do I have to put the JWT access token as a httpOnly cookie as well? Then I can retrieve the access token cookie in getServerSideProps.

But then this approach is vulnerable to CSRF as pointed out in this question: Where to store the refresh token on the Client?

Is there a possibility to make a solution with two httpOnly cookies (one for refresh and one for access token) secure?

Is it secure to set both cookies as httpOnly and samesite strict? and set the path of the refresh token cookie to /refresh-token only? So the refresh token cookie is only sent to /refresh-token and not everywhere else.

I have seen that there is the next-auth module there I can use the getSession function on serverside but since I have my own authentication service that handles all the token management I am not sure if it is a good idea or even possible to wire my own authentication system with next-auth.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
anvin
  • 450
  • 2
  • 8
  • 22
  • What solution did you find? – Ranu Vijay Feb 09 '22 at 21:39
  • I ended up using a `httpOnly` and `SameSite=Strict` cookie in combination with a `csrf` token in sensitive actions. If I would start over again I would look into next-auth with a custom provider to wire up nextjs with my api. – anvin Feb 11 '22 at 07:43
  • now nextauth has credentials functionality to login to the remote server via api and we can have returned user and key in the session :) :) – Ranu Vijay Feb 13 '22 at 21:43

1 Answers1

1

Depending on how your own authentication system works, if it adhere's to the oauth / openid-connect standards, you can simply use a custom oauth provider in next-auth.

Otherwise you could use their Credentials Provider which allows for even more customization.

ndom91
  • 719
  • 1
  • 9
  • 19