Nick Maddren
Nick Maddren

Reputation: 661

Simple Express JS API token

I'm wonder how I can implement a simple API auth token without need for users? I just want one token that I can authenticate by adding it as a parameter when I call my API.

All the current examples on Google seem to be over engineered for my needs. I have some data stored in MongoDB and I simply serve this data like so:

  app.get("/", (req, res) => {
    Car.find((err, cars) => {
      if(err){
        throw err;
      }
      res.json({"cars": cars});
    });
  });

Is it possible to add some simple middleware that checks my environment file for an element with the name of api_token. Then check that the api_token in my env file matches the parameter that has been passed as a URL query.

Is there a way to do this? I'm aware that you can't use URL queries on a GET route so I am unsure how this would work.

Upvotes: 0

Views: 897

Answers (2)

Allan Felipe Murara
Allan Felipe Murara

Reputation: 526

Remember, Tokens are responsible for at least 2 API security mandatory things, authenticate and authorize. You don't need to authenticate users, but you need to be sure that the token you received is a Token and not a "HEADER".

If you use a static token,or anything else, first time i get your token your security is down. You need to specify AT LEAST when this token will die, and if it is a valid one based on some random assignment. You can't check for it's presence, you need to check if it is valid.

Javascript has an amazing convention background, whenever you have the opportunity, follow the convention. It is easier as it seems to implement a JWT based.

Just follow this : https://github.com/auth0/node-jsonwebtoken

and implement it in your middleware as you wishh.

Easily as this /

jwt.sign({ exp: Math.floor(Date.now() / 1000) + (60 * 60), data: 'foobar' }, 'secret');

jwt.verify(token, 'shhhhh', function(err, decoded) { console.log(decoded.foo) // bar });

You can always redo the concepts by using a "Web HEADER" and calling it a "TOKEN". But as i said, it is a "Web Header" not an "WEB TOKEN".

Upvotes: 1

Cisco
Cisco

Reputation: 22952

Sure, use middleware: https://expressjs.com/en/guide/using-middleware.html

For your case, it can be as simple as the following:

// checkForApiToken.js
module.exports = (req, res, next) => {
  const apiToken = req.header("api-token");
  if (process.env.API_TOKEN !== apiToken) {
      next(new Error("Unauthorized."));
      return;
  }
  next();
}

The logic is simple:

  1. Retrieve API-TOKEN value from the header.
  2. Check it matches what I've defined in my env.
    • Does not match, throw an error by passing an error object into the next function.
  3. Matches so I call next() with no error to proceed to the next request handler.

You would then use it like so:

app.get("/", checkForApiToken, async (req, res) => {
    const cars = await Car.find().exec();
    res.json({ cars });
});

Upvotes: 1

Related Questions