I'm attempting to send a Passport-Local login request to the client side to be analyzed by Satellizer, and I would like the request from the server side to send an authorization token. Unfortunately, there is no key authorization
in request.headers
:
{ host: 'localhost:3000',
connection: 'keep-alive',
'cache-control': 'max-age=0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' }
The login function redirects here, and this is where ensureAuthenticated()
is called.
app.get('/main', ensureAuthenticated, function(req, res, next){
res.render('main.ejs', { token: createSendToken(req.user, config.secret), id: req.user._id, username: req.user.username, authorization: req.user.authorization });
});
ensureAuthenticated()
then analyzes the login request and makes sure the tokens match:
function ensureAuthenticated(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
}
var token = req.headers.authorization.split(' ')[1];
var payload = null;
try {
payload = jwt.decode(token, config.token_secret);
}
catch (err) {
return res.status(401).send({ message: err.message });
}
if (payload.exp <= moment().unix()) {
return res.status(401).send({ message: 'Token has expired' });
}
req.user = payload.sub;
next();
}
It then redirects and shows the message
{ message: 'Please make sure your request has an Authorization header' }
How would I set an authorization key to request.headers?
To set a new header field in the request just access it directly, as the headers object looks like a normal hash table.
request.headers.authorization = value;