Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set authorization in Node request.headers

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?

like image 782
Les Paul Avatar asked Feb 10 '16 12:02

Les Paul


People also ask

Can we send authorization header in request?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.

How do I pass the authorization header in node fetch?

You can pass HTTP headers to the fetch() request as the second parameter. For example, to pass the Bearer Token Authorization Header, call fetch() with the {headers: {Authentication: 'Bearer Token'}} parameter.

How do I authorize my header?

It is a simple authentication scheme built into the HTTP protocol. The client sends HTTP requests with the Authorization header that contains the word Basic, followed by a space and a base64-encoded(non-encrypted) string username: password. For example, to authorize as username / Pa$$w0rd the client would send.


1 Answers

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;
like image 80
bolav Avatar answered Oct 09 '22 20:10

bolav