Next Auth with external Node.js API

Viewed 1417

I am using Next Auth and have a standalone Node.js API running. I am using Next Auth using credentials and use axios to send the username and password to the API.

On the API side, if the username and password are correct, I set a session using express-session and save it to the database.

If the response status is 201 in Next.js I want to then add the express-session token from the API to my Next.js session.

The below code is working in that I authenticate and when I console.log session in protected pages I see the express-session token that was set on the server. This token is also stored in mongoDB. But is it correct? Is the purpose of this to protect routes on the frontend only ie: checking that there is a session in Next.js

If on the protected pages I need to make an API request, would I then check that session token against the database token for the logged in user?

And lastly, where does JWT fit in here, is this how Next.js is handling the client side auth sessions, using JWT?

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
export default NextAuth({
  session: {
    jwt: true,
    maxAge: 30 * 24 * 60 * 60,
  },
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        try {
          const response = await axios.post(`http://localhost:8000/login`, {
            email: credentials.email,
            password: credentials.password,
          });

          if (response.status === 201) {
            const user = {
              email: credentials.email,
              accessToken: response.data.token,
            };
            return user;
          } else {
            return null;
          }
        } catch (err) {
          console.log(err.response);
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.accessToken = user.accessToken;
      }
      return token;
    },
    async session({ session, token, user }) {
      session.accessToken = token.accessToken;
      return session;
    },
  },
});
2 Answers
export default NextAuth({
    providers: [
      CredentialsProvider({
        name: 'Credentials',
        credentials: {
          username: {label: 'Username', type: 'text', placeholder: 'email@site.com'},
          password: {label: 'Password', type: 'password', placeholder: 'password'},
        },
        async authorize({username, password}, _req) {
          try {
            const {data, error} = await fetch("<your-remote-api>")
            if (!data?.user || error) {
              return null
            }
            return data.user
          } catch (error) {
            return error
          }
        },
      }),
    ],
    callbacks: {
      jwt: async ({token, user}) => {
        if (user) {
          token.data = user
        }
        return token
      },
      session: async ({session, token}) => {
        if (token.data) {
          session.user = token.data
        }
        return session
      },
    },
  })

If on the protected pages I need to make an API request, would I then check that session token against the database token for the logged in user?

Yes you need to check that session but from what I undesrtand, the check of the session would be to just verify the token.. so no need to query your database.

And lastly, where does JWT fit in here, is this how Next.js is handling the client side auth sessions, using JWT?

That verification is done trough JWT.. basically JWT will make sure the token you are sending is the same it has created

Note: the only thing that I don't undesrtand yet is about role permission. JWT token can tell you if the user is authenticated. But if you update user role from a dashboard admin panel, let say from active to inactive, then at some point in your api you would need to request your db to check user's role. I don't think we can rely on the token in this case

Related