Answers for "authentication-and-authorization-using-jwt-in-node-js"

0

authentication-and-authorization-using-jwt-in-node-js

exports.verifyUserToken = (req, res, next) => {
    let token = req.headers.authorization;
    if (!token) return res.status(401).send("Access Denied / Unauthorized request");

    try {
        token = token.split(' ')[1] // Remove Bearer from string

        if (token === 'null' || !token) return res.status(401).send('Unauthorized request');

        let verifiedUser = jwt.verify(token, config.TOKEN_SECRET);   // config.TOKEN_SECRET => 'secretKey'
        if (!verifiedUser) return res.status(401).send('Unauthorized request')

        req.user = verifiedUser; // user_id & user_type_id
        next();

    } catch (error) {
        res.status(400).send("Invalid Token");
    }

}
Posted by: Guest on June-01-2021

Code answers related to "authentication-and-authorization-using-jwt-in-node-js"

Code answers related to "Javascript"

Browse Popular Code Answers by Language