next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

NextAuth.js with custom JWT

Open LucasOliveiraS opened this issue 5 years ago • 0 comments

NextAuth.js with custom JWT

What are you trying to do

I have an authentication backend that returns a JWT when the user performs authentication. I am trying to implement NextAuth to handle my JWT.

Following the documentation on Credentials, I was able to receive JWT through NextAuth. However, I have some doubts about this. Especially thinking about the best way to accomplish this.

  1. Should I change any options to inform NextAuht.js that I am using a custom JWT?
  2. To decode my JWT, I must modify the jwt options?
    jwt: {
        // async decode({ secret, token, maxAge }) {},
    }
  1. After performing the JWT decode, it is considered a good option to store the payload in the session?

Reproduction

My current application:

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'


const providers = [
  Providers.Credentials({
    id: 'app-login',
    name: 'ms-auth',
    credentials: {
      email: { label: "email", type: "text ", placeholder: "e-mail" },
      password: {  label: "Password", type: "password" }
    },
    authorize: async (credentials) => {
      const user = await login(credentials);

      if (user) {
        return user
      } else {
        return null
      }
    }
  })
]

const login = async (credentials) => {
  try {
    const user = await fetch('http://127.0.0.1:8000/user/login', {
      body: JSON.stringify({
        email: credentials.email,
        password: credentials.password
      }),
      headers: {
        'Content-Type': 'application/json'
      },
      method: 'POST'
    })

    const data = await user.json()

    if (user) {
      return {token: data.token.access_token}
    }
  } catch (error) {
    console.log(error)
  }
}

const callbacks = {
  async signIn(user, account, profile) {
    return true
  },

  // Getting the JWT token from API response
  async jwt(token, user) {
    if (user) {
      token.accessToken = user.token
    }

    return token
  },

  async session(session, token) {
    session.accessToken = token.accessToken
    return session
  }
}

const options = {
  providers,
  callbacks,
  secret: process.env.SECRET,
}

export default (req, res) => NextAuth(req, res, options)

Feedback

  • [x] Found the documentation helpful
  • [x] Found documentation but was incomplete
  • [ ] Could not find relevant documentation
  • [x] Found the example project helpful
  • [ ] Did not find the example project helpful

LucasOliveiraS avatar Mar 03 '21 21:03 LucasOliveiraS