Unable to verify token within JWT Express middleware

I am encountering an issue with the validation of JWT tokens. When sending a GET request using Postman, the validation process fails to work as expected. Surprisingly, the request can go through even without a token. My concern is regarding utilizing this validation in middleware. I am unsure of what might be going wrong with my code.

customerController :


    authenticate: async(req,res) => {
            var email = req.body.email
            var password = req.body.password
            let emailAuth = await customer.email_auth(email) 
            if(!emailAuth){
                return res.status(500).json({status: "Failed", message:"User not found"});
            }else if(emailAuth.password != password){
                return res.status(500).json({status: "Failed", message:"Authentication failed. Wrong password."});
            }else{
                const payload = {
                    user : emailAuth.id
                };
                // console.log(payload)
                var token = jwt.sign(payload, app.get('superSecret'),{
                    expiresIn: 60 // 1menit
                });

                // return information incl token on json
                res.json({
                    success: true,
                    message: token,
                    // token: token
                })
            }

        }

users.js :


     router.use(function(req,res,next){
            var token = req.body.token || req.query.token || req.headers['x-access-token'];

            if(token){
                jwt.verify(token, app.get('superSecret'), function(err,decoded){
                    if(err){
                        return res.json({success: false, message: 'Failed to authenticate token.'})
                    }else{
                        req.decoded = decoded
                        next()
                    }
                })
            }else{
                return res.status(403).send({ 
                    success: false, 
                    message: 'No token provided.' 
                });
            }
        }) 

app.js :


    const express = require('express');
    const jwt = require('jsonwebtoken')
    const app = express();
    const bodyParser = require('body-parser');
    const router = require('./app/routes/users')

    // Route
    app.use(bodyParser())
    app.use('/users', router)


    //// server listening
    const port = process.env.PORT || 3000;
    app.listen(port)
    console.log(`server listening at ${port}`);

Answer №1

To restrict access to certain routes to only logged-in users, you need to create a middleware with your code and include it in those specific routes.

The middleware you should use is called verifyToken.

var jwt = require('jsonwebtoken');
function verifyToken(req, res, next) {
  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  if(token){
    jwt.verify(token, app.get('superSecret'), function(err,decoded){
      if(err){
        return return res.status(403).send({ 
          success: false, 
          message: 'Failed to authenticate.' 
        });
      }else{
        req.decoded = decoded
        next()
      }
    })
  }else{
    return res.status(403).send({ 
      success: false, 
      message: 'No token provided.' 
    });
  }
}
module.exports.verifyToken = verifyToken;

In your app.js file, you can apply the verifyToken middleware to the /users route as follows:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const router = require('./app/routes/users')
const verifyToken = require('./your-middleware-path')

// Route
app.use(bodyParser())
app.use('/users', verifyToken, router)


//// server listening
const port = process.env.PORT || 3000;
app.listen(port)
console.log(`server listening at ${port}`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The web forms on my shared hosting account are set up to send emails via SMTP to my designated email address, but they are unable to send to providers such as Gmail

After conducting a search, I am still struggling to find the right solution... I have encountered an issue with setting up web forms using Node.js (express) and PHP. The problem lies in sending form data to email addresses outside of my domain. Despite su ...

Issue with Authentication - Sequencing of Observables and Promises in Angular/REST APIs

I'm currently utilizing Angular 7 and have recently started working on a new Angular application project at my agency. One of my colleagues has already set up the backend (Restful), so I began by focusing on implementing the Authentication Feature. T ...

Using cookies for authentication in Angular 5

Currently, I am in the process of building a website with Angular 5 and Express JS. One issue I am facing is that after a successful login, the access_token cookie is being sent from the server to the client. Although the cookie is successfully set in th ...

Would ReactJS (or NextJS) be a good fit for a traditional website?

Would using reactjs (or nextjs) be a suitable choice for creating a classic website? I am planning to develop a website for a kindergarten. Is it a good or bad idea to proceed with using react, considering it will be a multiple page app? Or would it be bet ...