Search code examples
next.jsauth0next-auth

Set and Get Token from the session on nextauth athentication with auth0


I have a nextjs app. I am authenticating using nextauth and Auth0Provider.

I want to be able to get the token and send it via headers for my api requests. I can log and see the token on the signIn callback but I can not access the same in the session callback. I think I am missing something and I would appreciate any help I can get.

[...nextauth].js

import NextAuth from 'next-auth';
import Auth0Provider from 'next-auth/providers/auth0';

export default NextAuth({
  providers: [
    Auth0Provider({
      clientId: 'pF....H',
      clientSecret: 'Mh.....vAbQ',
      issuer: 'https://dev-xceoh....8u8.us.auth0.com',
      redirectUri: `http://localhost:3000/api/auth/callback/auth0`,
      idToken: true,
      token: {
        params: {
          audience: 'https://dev-xce.....r8u8.us.auth0.com/api/v2/'
        }
      },
      authorization: {
        params: {
          audience: encodeURI('https://dev-x......r8u8.us.auth0.com/api/v2/')
        }
      }
    }),
  ],
  secret: '306.................024',
  session: {
    strategy: 'jwt',
    secret: process.env.NEXTAUTH_SECRET
  },
  jwt: {},
  callbacks: {
    session: async ({ session, token }) => {
      if (token) {
        session.user = token.user;
        session.accessToken = token.accessToken;
        session.error = token.error;
      }
      return session;
    },
    async redirect(url) {
      if (typeof url === 'string') {
        return url.startsWith('http://localhost:3000') ? url : 'http://localhost:3000';
      } else {
        return 'http://localhost:3000';
      }
    },
    async jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token
      }
      return token
    },
    async signIn( profile) {
      if (profile?.account?.access_token) { // Check if the token exists in the account object
        console.log('ACCESS TOKEN!!!!!!!:', profile.account.access_token); // Log the token to the console
        return '/apps';
      }
      return true;
    },

  },
});

Index.js

<div className="flex flex-col items-center justify-center mb-4">
  <img src={logoUrl} alt="Logo" />
  <a href="/api/auth/signin" className="mt-2 text-blue-500 hover:underline"
    onClick={(e) => {
      e.preventDefault();
      signIn("auth0");
    }}>
  Log in
  </a>
</div>

Solution

  • I have been able to get it using getSession() hook.

    import { getSession } from 'next-auth/react';
    
      export function authHeaders() {
        if (typeof window !== 'undefined') {
          return getSession()
            .then(session => {
              const token = session.accessToken;
              console.log("THE TOKEN BEING SENT IS!!!!!!!!!!",token)
              const authToken = `Bearer ${token}`;
              return {
                headers: {
                  Accept: 'application/json',
                  'content-type': 'application/json',
                  Authorization: authToken,
                },
              };
            })
            .catch(error => {
              console.error('Error fetching session:', error);
              // Handle error case: return headers without Authorization if token retrieval fails
              return {
                headers: {
                  Accept: 'application/json',
                  'content-type': 'application/json',
                },
              };
            });
        }
      }