jwt node api authentication code example

Example 1: 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");
    }

}

Example 2: token authentication in nodejs

If the request contains the access token, then the server will verify whether it was issued by the server itself using the stored secret. In case the token is expired or recognized as a one not signed by the server, the jsonwebtoken’s verify method will throw an error. We can handle the error to return a 401 error back to the client.