admin管理员组

文章数量:1406160

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?

本文标签: nodejsJWT Token Verification Fails with 39invalid signature39 in Expressjs MiddlewareStack Overflow