I have an authentication route on my Node.js server that authenticates requests:
app.get('/loggedin', auth, function(req, res){
console.log(req.authenticated);
res.send(req.authenticated ? req.authenticated: false)
})
As I understand it, auth
is run before app.get()
. Here is the code for auth
:
var jwt = require('jsonwebtoken');
var config = require('./config');
module.exports = function(req,res,next){
var bearerHeader = req.headers['authorization'];
var token;
console.log(bearerHeader);
req.authenticated = false;
if (bearerHeader){
console.log("11111");
var bearer = bearerHeader.split(" ");
token = bearer[1];
jwt.verify(token, config.secret, function (err, decoded){
console.log("22222");
if (err){
console.log(err);
req.authenticated = false;
req.decoded = null;
} else {
console.log("33333");
req.decoded = decoded;
req.authenticated = true;
}
});
}
next();
}
On the server log, however, I receive the following output:
Bearer jsflkdjlsdfjksodfkjlsdfjkls
11111
false
22222
33333
This means that there is a token on the client's side, and that is passes the jwt verification. However, the server decides to begin running app.get()
before it finishes returning information in the authentication callback. What gives?