admin管理员组

文章数量:1404564

I am using NextAuth for authentication in my Next application and in a separate express server i am trying to decode the jwt and get the playload data but if always shows Token verification failed: JWSInvalid: Invalid Compact JWS this is the next auth code

async jwt({ token, account, profile }: { token: any; account: Account; profile: Profile }) {
            if (account?.provider && profile) {
                // Convert GitHub ID to string to match schema's Int type
                const providerId = account.provider === 'github'
                    ? parseInt(profile.sub as string, 10)
                    : profile.sub;

                const user = await db.user.findUnique({
                    where: {
                        provider_provider_id: {
                            provider: account.provider.toUpperCase(),
                            provider_id: providerId?.toString() || ''
                        }
                    }
                });

                if (user) {
                    // token.sub = user.id;
                    token.role = user.role;
                    token.sub = user.id.toString();
                }
            }
            return token;
        },
        async session({ session, token }: { session: any, token: any }) {
            if (token.id && token.role) {
                session.user.id = token.id;
                session.user.role = token.role;
            }
            return session;
        },

and this is the express middleware where i am trying to get the token

import { NextFunction, Request, Response } from "express";
import { jwtVerify } from "jose";
import dotenv from 'dotenv';
dotenv.config();

export const AuthMiddleware = async (req: Request, res: Response, next: NextFunction) => {
  const token = req.cookies["__Secure-next-auth.session-token"] || req.cookies["next-auth.session-token"];

  if (!token) {
    return res.status(401).json({ message: "No token received" });
  }

  console.log("Token Structure:", token.split('.').length);

  try {
    const secretStr = process.env.NEXTAUTH_SECRET;
    if (!secretStr) throw new Error("NEXTAUTH_SECRET is missing");

    console.log("Using secret:", secretStr);

    const { payload } = await jwtVerify(token, new TextEncoder().encode(secretStr), {
      algorithms: ['HS256']
    });

    if (!payload.sub || !payload.role) {
      return res.status(401).json({ message: "Invalid token payload" });
    }

    req.user = { 
      userId: payload.sub,
      role: payload.role as string 
    };
    console.log("Verified payload:", payload);
    next();
  } catch (error) {
    console.error("Token verification failed:", error);
    return res.status(401).json({ message: "Invalid token" });
  }
};

can't get the info here

本文标签: nodejsHow to get the jwt payload in express server generated by NextAuthStack Overflow