Search code examples
node.jsexpressjson-web-token

Express Middleware jsonwebtoken authentication


My server has a registration api that provides a token after registration, and a middleware that authenticates a user's token. I need to register an account to get the token to do something else with my server. However, the middleware blocks my network request because I don't have a token yet.

So how can I create my account and token in this case? Get pass the middleware with some tricks?

Middleware:

  // Middleware to verify token, it will be called everytime a request is sent to API
  api.use((req, res, next)=> {
    var token = req.headers.token
    if (token) {
      jwt.verify(token, secret, (err, decoded)=> {
        if (err) {
          res.status(403).send({ success: false, message: "Failed to authenticate user." })
        } else {
          req.decoded = decoded
          next()
        }
      })
    } else {
      res.status(403).send({ success: false, message: "No Token Provided." })
    }
  })

Signin:

  // Sign In with email API
  api.post('/signInWithEmail', (req, res)=> {
    User.findOne({
      email: req.body.email
    }).select(userFields).exec((err, user)=> {
      if(err) {
        throw err
      }
      if (!user) {
        res.send({ message: "User doesn't exist"});
      } else if (user) {
        var validPassword = user.comparePassword(req.body.password);
        if (!validPassword) {
          res.send({ message: "Invalid Password"});
        } else {
          var token = createToken(user);
          res.json({
            success: true,
            message: "Login Successfully!",
            token: token
          })
        }
      }
    })
  })

Solution

  • Make a function to check tokens and expose your routes such that whenever you need to call an authenticated route then you'll be checking the token first and then you'll expose the route.

    Sample Code

    Let's say this is my check token function

    function checkToken(req, res, next) {
    var x = req.token; //This is just an example, please send token via header
        if (x === token)
        {
           next();
        }
        else
        {
           res.redirect(/unauthorized); //here do whatever you want to do
        }
        }
    

    Now let's use the function for routes.

    app.post('/protectedroute', checkToken, routename.functionname);
    app.post('/notprotected', routename.functionname);
    

    It's your call if you'd like to have separate routes for different codes or else you can just call specific code block via keeping them in function etc. on the main file i.e. app.js or server.js, whatever you have chosen.

    What actually we are doing here is - we are making a middleware of our own to expose our routes through a channel of code blocks or functions.