dwyl / learn-json-web-tokens

:closed_lock_with_key: Learn how to use JSON Web Token (JWT) to secure your next Web App! (Tutorial/Example with Tests!!)
MIT License
4.18k stars 254 forks source link

How to exclude some routes from jwt token verification #77

Open ashrafkm opened 7 years ago

ashrafkm commented 7 years ago

I am using jsonwebtoken module How to exclude a route from jwt token verification

router.use('/loginRegistration', mountAllRoutes(loginRegistration));

router.use((req, res, next) => {
const r = req;
// check header or url parameters or post parameters for token
// const token = req.body.token || req.query.token || req.headers['x-access-token'];
const token = req.body.token || req.query.token || req.headers.authorization;
// decode token
if (token) {
    // verifies secret and checks exp
    jwt.verify(token, req.app.get('superSecret'), (err, decoded) => {
        if (err) {
            // res.json({ success: false, message: 'Failed to authenticate token.' });
            return res.status(401).send({
                success: false,
                message: 'Failed to authenticate token.'
            });
        } else {
            // if everything is good, save to request for use in other routes
            r.decoded = decoded;
            next();
            // console.log(decoded);
        }
        // return {};
    });
} else {
    // if there is no token
    // return an error
    return res.status(403).send({
        success: false,
        message: 'No token provided.'
    });
}
});

router.use('/test', mountAllRoutes(testModule)); router.use('/other', mountAllRoutes(otherModule)); router.use('/users', mountAllRoutes(userModule)); router.use('/data', mountAllRoutes(dataModule));

Here Whatever I put after token verify code, it works perfect. It asks token. But which I put above jwt token verify code, for that also it asks token. I mean for user registration it says token not provided but in database user will be created.

image

Here above for user creation, it gives response "No token provided" but if I see database then that user details will be created. Please tell me how can I resolve it