How to set authorization headers with nodejs and express How to set authorization headers with nodejs and express mongoose mongoose

How to set authorization headers with nodejs and express


If you want the client to include the token in it's request headers, you can use a cookie parser with express. (HTML5 Web Storage is another option). About Cookies:

Express can set the response headers to tell the client "add the token to a cookie".

Once the client sets the cookie with the token, the token will be in the client's request headers for each request. Let's get to baking with a little

npm install cookie-parser

Sprinkle on some

var cookieParser = require('cookie-parser')app.use(cookieParser())

Access and set a cookie:

app.use(function (req, res, next) {  var cookie = req.cookies.jwtToken;  if (!cookie) {    res.cookie('jwtToken', theJwtTokenValue, { maxAge: 900000, httpOnly: true });  } else {    console.log('let's check that this is a valid cookie');    // send cookie along to the validation functions...  }  next();});

You will probably want to do these things with the cookies (or whatever method you go with in the end):

  • set the cookie to hold the token when a user is authenticated.
  • check the cookie header value before allowing access to protectedroutes.
  • send back an unauthorized status if a user doesn't have their tokenwhen they are trying to access api routes that require a token.