4

I am trying to use NextAuth as auth provider for my project. I have a requirement where I have Credential based login/password. In this case when I login I have to pass the username/password to the custom API (for ex.: abc.com/auth/login). This API as success will return me a JWT for future communication to access their resources.

What I understood from NextAuth that it maintain its own session and JWT(if DB not provided). This feature works in my case but I have to maintain the JWT which the API has returned me(mentioned above). So now there are two JWT one which I received from API and the one which NextAuth has created.

My question:

  • Is there a way which I can use to maintain the custom JWT which I received from API?
  • Is there a way if API token has been expired to tempered so I can kill NextAuth session.
  • What is the best way to keep NextAuth Session and Custom JWT token in sync?

Thanks in advance!

1 Answer 1

3

Got the answer on Next-auth repo discussions itself.

This solution worked for me.

So, we can let next-auth generate the JWT token which contains the same payload as the one provided by the API (We can disable the token signature verification in the API).

Then update the next-auth configuration to have a save token in cookie has httpOnly: false so we can access the token server and client sides by adding it in the configuration:

const options = {
   // ...
   cookies: { sessionToken: { name: `next-auth.session-token`, options: { httpOnly: false } } },
}

After that we can use the code to get the JWT token to be passed to the API calls from the server and client sides:

import cookies from 'next-cookies'
import Cookies from 'js-cookie'

// Server-Side
cookies(context)['next-auth.session-token']
// Client-side
Cookies.get('next-auth.session-token')

Now we just need to figured out how to save my JWT token provided by my API instead of using the one generated by next-auth.

Then we will be able to reactivate the signature verification in the backend API.

You can follow the thread here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.