node.jsjwtrestify

JWT Verify Causing ERR_HTTP_HEADERS_SENT


We are developing a ReST API using Restify (Node.js). As part of the authentication mechanism, we developed a middleware whose purpose is to screen incoming tokens and verify them. However, looking at the logs, multiple errors related to ERR_HTTP_HEADERS_SENT are popping up.

Here is the code for the middleware:

var client = jwksClient({
    strictSsl: false, 
    jwksUri: process.env.JWKS_URI
})

// Route middleware to verify a token
server.use(
    async (req, res, next) => {

        let path = req.route.path.replace(/\?.*$/,'')

        let url = req.url

        let whitelist = [
            // list of endpoints that are left unprotected
        ]

        if(whitelist.indexOf(path) > -1 || whitelist.indexOf(url) > -1){
            return next()
        } 
        else {
            const r = req
            let token = req.headers['x-access-token'] || req.headers['authorization']
            
            // Decode token
            token = token.slice(7,token.length).trimLeft()
            
            token = token.trim()

            if (token == undefined || token.length <= 0) {
               res.send(401)
               return
            }

            try{
                // Verify the token
                jwt.verify(
                    token, 
                    getKey, 
                    {
                        algorithm: process.env.JWT_ALGORITHM
                    }, 
                    (err, decoded) => {
                        if (err) {
                            res.end(401)
                            return
                        } 
                        else{
                            next()
                        }
                })    
            }
            catch(e){
                res.send(401)
                return
            }

            let email = jwtDecode(token)['email']
    
            // Code here to query database and check whether email is registered
            
            // If no result has been returned
            if (email != null && email != undefined && email.length > 0) {
                return next()
            }
            else {
                res.send(401)
                return
            }
        }   
})

We're using jsonwebtoken as the library to do the verification.


Solution

  • What happen is that your using the callback, and the rest of the function keep going on, so untill the callback happens your already sending the headers

                try{
                    // Verify the token
                    jwt.verify(
                        token, 
                        getKey, 
                        {
                            algorithm: process.env.JWT_ALGORITHM
                        })
                     return next()
                }
                catch(e){
                    res.send(401)
                    return
                }