最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - JWT Token Verification Fails with 'invalid signature' in Express.js Middleware - Stack Overflow

programmeradmin0浏览0评论

I am working on an Express.js application where I use JWT for authentication. My authentication and verification setup works fine in Postman, but when I try to make requests from my frontend, I get the following error in my backend console:

JsonWebTokenError: invalid signature
    at C:\Users\lanci\node_modules\jsonwebtoken\verify.js:133:19  
    at getSecret (C:\Users\lanci\node_modules\jsonwebtoken\verify.js:90:14)
    at module.exports [as verify] (C:\Users\lanci\node_modules\jsonwebtoken\verify.js:94:10)
    at authMiddleware (file:///C:/Users/lanci/Desktop/Application_MyTicket/Admin_Dashboard/React-CRUD-Operation/anisateur_backend/middleware/auth.js:21:25)

Here is my JWT token generation code in authController.js:

import jwt from "jsonwebtoken";

const generateToken = (user) => {
    return jwt.sign(
        { id: user.id, role: user.role },
        process.env.JWT_SECRET,
        { expiresIn: "1h" }
    );
};

// Example usage in login
const login = async (req, res) => {
    // User authentication logic
    const token = generateToken(user);
    res.json({ token });
};

I have verified that:

process.env.JWT_SECRET is correctly loaded in both server.js and auth.js. The token works fine in Postman, but fails when making requests from the frontend. When pasting the token into jwt.io, the signature shows as invalid. Restarting the server and regenerating a new token does not solve the issue. What could be causing this error? How can I ensure the token verification works properly in both Postman and the frontend?

发布评论

评论列表(0)

  1. 暂无评论