Pranay Sharma
Pranay Sharma

Reputation: 29

validating the invalid token in expressJWT

I added a middleware in my API using express JWT. now the problem is when the user sends an invalid token, I got an error 'Unauthorized Error'. what I want is to send and respond to the user when they pass the wrong token.

My ExpressJWT middleware

exports.isUserSignedIn = expressJWT({
    secret: process.env.SECRET,
    userProperty: "auth",
    algorithms: ["HS256"],
})

I used this middleware like this in my routes

`` router.get("/get/notifications",[isUserSignedIn], getUserNotification)

Upvotes: 1

Views: 541

Answers (1)

Pranay kumar
Pranay kumar

Reputation: 2197

You can use the JWT token verify method to verify the token.

Here is the middleware which can handle empty token as well as an invalid token.

exports.checkJWT = (req, res, next) => {
    if (!req.headers.authorization) {
        return res.status(403).json({
            message: 'No credentials sent!'
        });
    } else {
        let bearer = req.headers.authorization;
        let token = bearer.split(" ");
        jwt.verify(token[1], process.env.SECRET, function (err, decoded) {
            if (err) {
                return res.json({
                    message: "Invalid token"
                })
            } else {
                next();
            }
        });
    }
}

You can use this middleware in your routes like this.

router.get("/get/notifications",[checkJWT], getUserNotification)

Upvotes: 1

Related Questions