Authentication for protected routes using express/jwt

Viewed 139

When the user logins, the access token is created and sent to the user, it is then stored in sessionStorage. Everything before this works fine. My problem is that I do not know how to use the access token to gain access to protected routes.

express app.js (smoothies is the protected route)

app.get('/smoothies', requireAuth, (req, res) => res.render('smoothies'));

authMiddleware.js

const User = require('../models/User');

const requireAuth = (req, res, next) => {
  const authHeader = req.headers['authorization']

  const token = authHeader && authHeader.split(' ')[1]
  // check json web token exists & is verified
  if (token) {
    jwt.verify(token, 'night of fire', (err, decodedToken) => {
      if (err) {
        console.log(err.message);
        res.redirect('/login?err=auth');
      } else {
        console.log(decodedToken);
        next();
      }
    });
  } else {
    res.redirect('/login?err=auth');
  }
};

// check current user

module.exports = { requireAuth };

smoothies.ejs

  var myHeaders = new Headers();
  myHeaders.append("Authorization", `Bearer ${token}`);

  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

  fetch("http://localhost:3000/smoothies", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
//Should I be even doing this fetch GET request on smoothie.ejs? 

 })

Smoothies is the protected route. When I try to use Postman and send a GET request to (/smoothies) using authorization : bearer token, it works and I am able to access /smoothies. However, if I try on the real application, I was denied access even with access token in my sessionStorage. When I console.log req.headers['authorization'], it was undefined so I am guessing my GET request from smoothie.ejs does not work. Does anyone know what is the solution?

0 Answers
Related