b26
b26

Reputation: 198

Having issues with JWT and express-JWT

I'm testing out express-jwt and jsonwebtokens. I've never used this before and would like some help!

I've got the basics setup done and I only have one protected route.

app.use('/api', expressJWT({secret: 'cat'}));

Unfortunatley, i'm not able to access '/api' because it gives me this error

UnauthorizedError: No authorization token was found

If I use POSTman and issue a GET request with the following header

Authorization -> Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJhc2hpciIsImlhdCI6MTQ1MTQ0MjM4NywiZXhwIjoxNDUxNDQyNjg3fQ.CnaLvS_oCEy_mp_9MSAmTTylJqQMI2Qlq9V3emAmN3E

Everything works fine and I'm able to access the content in '/api'.

But my issue is in my express application, specifically when I try to redirect the user to a new protected route.

User logs in and I create a new jwt token and redirect the user to '/api'

router.post('/login', passport.authenticate('local'), function (req, res) {
    myToken = jwt.sign({
      username: req.body.username
    }, 'cat', {expiresIn: 60*5});
    res.redirect('/api');
});

In this route, I set the headers and render the page.

router.get('/api',  function (req, res) {
  res.render('index', {user: req.user});
});

Unfortunately, I get the following error

UnauthorizedError: No authorization token was found

My goal is to be able to redirect a user to a protected route.

From my understanding, since /api is a protected route, express-jwt should be setting my authorization headers. Even if I try to manually set my headers using a middleware I still get an error.

Any help is greatly appreciated!

Thanks!

Upvotes: 0

Views: 4707

Answers (1)

João Lima
João Lima

Reputation: 430

try something like res.redirect('/api?token ' + myToken);

Then to receive query inputs change the expressJWT normal function with a custom function.

app.use('/api', expressJWT({
  secret: 'cat',
  credentialsRequired: false,
  getToken: function fromHeaderOrQuerystring (req) {
    if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        return req.headers.authorization.split(' ')[1];
    } else if (req.query && req.query.token) {
      return req.query.token;
    }
    return null;
  }
}));

This was mostly from reading the expressJWT docs and other stack answers.

Upvotes: 2

Related Questions