#NextAuth Store and Access JWT

3 messages · Page 1 of 1 (latest)

viscid glacier
#

Hello, i do have created NextAuth with few providers and everything works fine but i do have issues reading the JWT that is passed from custom backend to me after succesfully login.

This is the CustomProvider implementation:

CredentialsProvider({
      name: 'Credentials',
      credentials: {
        email: {
          label: 'Email',
          type: 'email',
          placeholder: '[email protected]',
          value: '[email protected]'
        },
        password: {
          label: 'Password',
          type: 'password',
          value: 'register_password_123456'
        }
      },
      async authorize(credentials, req) {
        if (!credentials?.email || !credentials.password) {
          return null;
        }

        const response = await fetch(baseUrl, {
          method: 'POST',
          body: JSON.stringify({
            email: credentials.email,
            password: credentials.password
          }),
          headers: { 'Content-Type': 'application/json' }
        });

        const respData = await response.json();

        if (response.ok && respData.data.accessToken) {
          return respData.data;
        }

        return null;
      }
    })

respData.data.accessToken - contains server JWT

And then i'm trying to create a middleware that will read the token and apply it as a Authorization header

middleware.ts

// Without a defined matcher, this one line applies next-auth

import { NextMiddleware, NextRequest, NextResponse } from 'next/server';

// to the entire project
export { default } from 'next-auth/middleware';

import { getToken } from 'next-auth/jwt';

export const middleware: NextMiddleware = async (req) => {
  const token = await getToken({ req });
  console.log('token', token);
};

export const config = { matcher: ['/extra'] };

but this is what i get from the log of the token:

token {
  iat: 1698234422,
  exp: 1700826422,
  jti: '9af2c7bc-00a8-446d-9d2c-04b14acff1c5'
}
merry galeBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

viscid glacier
#

Any ideas what i'm doing wrong and is it correct this approach at all? How to get the jwt that is returned from my server and then set it as a Authorization: Bearer {jwt} header in the request. Thanks in advance! 🚀