Search code examples
node.jsexpressmongoosejwtswig-template

How to set authorization headers with nodejs and express


I am setting up a site with nodejs, express, mongoose and swig template following this tutorial : Authenticate a Node.js API with JSON Web Tokens

In this tutorial the author uses Postman to set the token in the header. I have googled for days to find out how I can set the jwt token in the header of my site, but it is not working for me.


Solution

  • 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 protected routes.
    • send back an unauthorized status if a user doesn't have their token when they are trying to access api routes that require a token.