Protect your HTTP requests using Node and JWT

Protect your HTTP requests using Node and JWT

If you ever switched from one technology to another you probably found your self asking how I'm doing… like I was doing in the previous technology…

I was writing in C# for many years, In the past two years I am playing with Node, one of the missing things in Node is the "attribute" mechanism - the one that allows you to place a decorator on a top of service, an that decorator holding execution logic's behind, and every service call that logic’s fires before get into the service,

Lately I had to straggle how to protect authorized HTTP requests, I wanted to do it nice and elegant like the [authorized] attribute from C#, I mean, I searched for solution where you can "mark" the requests that you want to protect while the rest will be open to the world, for anonymous users,

The source code for this post in autorized-sample link

The Node JS middleware layer provide several convention to handle HTTP routes:

app.get('/route', handler)
app.get('/route', [middleware], handler)
app.get('/route', [middleware1, middleware2 ..], handler)

HTTP method for which the middleware function applies where Node handle the GET, POST, PUT, DELETE and etc. HTTP methods.

Path (route) is actually the identify of the operation whiting the the stack which identify by the HTTP method.

The middleware handler is a function usually with 3 arguments:

  1. Request argument - an object which handle with HTTP request.
  2. Response argument - an object which handle with HTTP response
  3. Next argument - is actually Callback function that tells to the middleware to keeps to the next operation in the execution flow.

Although the first is the must common in use, for our case we will use the second convention with [middleware] which let you to run piece of code before you getting into the router handling.

Then, all the HTTP requests that we want to protect should look like:

app.get|post|put|delete, ... ('/some route', Authorized, handler)

Where Authorized looks (Typescript):

export function Authorized(request: Request, response: Response, next: NextFunction) {
  verify(request)
    .then(token => {
      next(token);
    })
    .catch(err => {
      response
        .status(401)
        .json({
          message: "Invalid credentials"
          errors: errors.fromJwtError(err)
        });
    });
}

function verify(request: Request): Promise<any> {
  let defer = deferred();
  var headers = (request.headers as any);
  var token = headers.authorization && headers.authorization.split('Bearer').pop().trim() || request.cookies["X-Authorization"];
  if (!token) {
    defer.reject("No authorization token was found");
  } else {
    jwt.verify(token, config.jwtSecret, function (err, decoded) {
      if (err) {
        defer.reject(err);
      } else {
        defer.resolve(decoded);
      }
    });
  }
  return defer.promise;
}

Meaning, every protected resource will first go to Authorized where is verify if the JWT is valid if "Yes" continue otherwise is return 401 - UNAUTHORIZED HTTP response

To view or add a comment, sign in

More articles by Shlomi Elbaz

  • Python Interpreter

    Script Interpreter implements in Python This is my attempt to create a new programing language, the language called…

  • Is jQuery still relevant?

    I had an interview and I was asked if I would start a new project do I choose to use jQuery? my immediate and intuitive…

    1 Comment
  • Parse urlencoded string into JSON in ONE line of code

    The source code can be found in: https://github.com/shlomisderot/url-encoded I would like to share with you some regex…

    3 Comments
  • Using Cencha CMD as development environment aid

    One of the common mistakes developers make is jumping into the code "to see things happening", that's OK if you have…

Others also viewed

Explore content categories