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
版权声明:本文标题:node.js - How to get the jwt payload in express server generated by NextAuth - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744839395a2627828.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论