Friday, November 18, 2022
HomeWeb DevelopmentUnderstanding API key authentication in Node.js

Understanding API key authentication in Node.js


When constructing an API with Node.js, there are totally different choices accessible concerning authentication. A few of these embody the JSON Net Token, OAuth, the API key, and extra. On this article, we’ll learn to authenticate a Node.js API utilizing API Keys.

Utilizing API keys has a bonus if you wish to set a restrict or monitor how typically a specific consumer is utilizing an API. By utilizing API keys, the consumer doesn’t want to fret about multi-factor authentication with their username and password. Your API’s consumer will be capable of automate knowledge fetching on the applying.

On this tutorial, we’ll create an API with Node.js. Then, we’ll create an authentication system that creates an API key each time a consumer registers on the applying. With the newly created API key, the consumer will be capable of entry all the routes on the API.

You will discover the whole code on GitHub. To comply with together with this text, you’ll want:

  • Fundamental data of Node.js
  • Node.js put in in your machine

Desk of contents

Preliminary venture setup

First, we’ll deal with all of the set up and preliminary setup to run our software. We’ll use Specific to develop the API and Nodemon to run the API server and hear for modifications within the code in real-time.

We’ll have to put in them, however first, create a folder to your venture and run the next command to create a bundle.json file to your venture:

$ npm init -y

Now, replace the "scripts" module in your bundle.json file with the code under in order that we’ll be capable of run the server with Nodemon:

...
"scripts": {
    "take a look at": "echo "Error: no take a look at specified" && exit 1",
    "dev": "nodemon Server.js"
  }
...

Later within the article, we’ll create the Server.js file the place we’ll run the server from. Now, set up Nodemon and Specific by working the next command:

npm set up categorical nodemon

Construct an authentication system

The authentication system takes in a given username and creates consumer knowledge, containing the username, API key, and a rely of utilization on a specific day. We’ll want the rely in order that we will set a restrict on what number of occasions a consumer can use the API on a specific day.

We’ll begin by making a perform referred to as genAPIKey() that generates the API when a brand new consumer is created. The perform will generate a base-36 string that incorporates 30 characters inside A-Z and 0-9, which is able to characterize the API key. You can begin by creating a brand new JavaScript file referred to as apiAuth.js and pasting the next code:

const genAPIKey = () =>  0).toString(36))
    .be part of('');
;

Subsequent, we’ll develop a perform that creates the consumer knowledge when a username is entered. We‘ll retailer this new consumer in an array, so we’d like some preliminary knowledge to get began. Create a brand new file referred to as initialData.js and paste the next code:

const customers = [
  {
    _id: 1587912,
    api_key: "rwuy6434tgdgjhtiojiosi838tjue3",
    username: "username",
    usage: [{ date: "2022-10-10", count: 17 }],
  },
];
const Nations = [
  { _id: 1, name: "Nigeria" },
  { _id: 2, name: "China" },
];
module.exports = { customers, Nations };

Now, we’ll develop the perform that creates a consumer by pasting the next code within the apiAuth.js file:

const customers = require('./initialData').customers; // import preliminary knowledge
...

const createUser = (_username, req) => {
  let right this moment = new Date().toISOString().break up('T')[0];
  let consumer = {
    _id: Date.now(),
    api_key: genAPIKey(),
    username: _username,
    utilization: [{ date: today, count: 0 }],
  };

  console.log('add consumer');
  customers.push(consumer);
  return consumer;
};

Subsequent, we’ll develop a perform that can authenticate the API key so as to entry specified components of the API. This perform will examine the registered API key with the x-api-key, which is able to include the request.

If the request goes by way of, the rely per day will increase, and in case you’ve reached your max request per day, you’ll obtain an error. Paste the next code into your apiAuth.js file:

const authenticateKey = (req, res, subsequent) => {
  let api_key = req.header("x-api-key"); //Add API key to headers
  let account = customers.discover((consumer) => consumer.api_key == api_key);
  // discover() returns an object or undefined
  if (account) {
    //If API key matches
    //verify the variety of occasions the API has been utilized in a specific day
    let right this moment = new Date().toISOString().break up("T")[0];
    let usageCount = account.utilization.findIndex((day) => day.date == right this moment);
    if (usageCount >= 0) {
      //If API is already used right this moment
      if (account.utilization[usageCount].rely >= MAX) {
        //cease if the utilization exceeds max API calls
        res.standing(429).ship({
          error: {
            code: 429,
            message: "Max API calls exceeded.",
          },
        });
      } else {
        //haven't hit todays max utilization
        account.utilization[usageCount].rely++;
        console.log("Good API name", account.utilization[usageCount]);
        subsequent();
      }
    } else {
      //Push todays's date and rely: 1 if there's a previous date
      account.utilization.push({ date: right this moment, rely: 1 });
      //okay to make use of once more
      subsequent();
    }
  } else {
    //Reject request if API key would not match
    res.standing(403).ship({ error: { code: 403, message: "You not allowed." } });
  }
};
module.exports = { createUser, authenticateKey };

We’re exporting in order that the Server.js can use these capabilities.

Develop routes for the server

On this part, we’ll create the routes that we’ll use to entry the information within the API whereas making use of the API key checks. We’ll create endpoints to register a consumer, add nations to the nation listing, and likewise get the listing of nations. Requests so as to add or get nations would require API key authentication.

To get began, create a brand new file referred to as Server.js and paste the code under. The code incorporates imports that we’ll use in a while, in addition to what shall be outputted on the homepage:

const categorical = require('categorical');
const app = categorical();
const port = 4000;
const API = require('./apiAuth');

// Get preliminary knowledge for customers and nations
const { customers, Nations } = require('./initialData');
//deal with json physique request
app.use(categorical.json());

app.get("https://weblog.logrocket.com/", (req, res) => {
  //house web page
  res.standing(200).ship({ knowledge: { message: 'You will get listing of countires at /api/nation.' } });
});

Utilizing the createUser() perform we developed earlier, we’ll create a route that can add new customers to the consumer listing and generate the consumer knowledge. Paste the next code in your Server.js file:

...
app.submit('/api/register', (req, res) => {
  //create a brand new with "consumer:Username"
  let username = req.physique.username;
  let consumer = API.createUser(username, req);
  res.standing(201).ship({ knowledge: consumer });
});

Now, we’ll develop the routes to create and get nations. On this route, we’ll embody the authenticateKey() perform we developed earlier in order that the API key despatched within the header of the request may be authenticated and the request may be counted. Then, we’ll lastly set the port that the server ought to hear on. Paste the next code in your Server.js file:

app.get('/api/nation', API.authenticateKey, (req, res) => {
  //get listing of all Nations   
  let right this moment = new Date().toISOString().break up('T')[0];
  console.log(right this moment);
  res.standing(200).ship({
    knowledge: Nations,
  });
});
app.submit('/api/nation', API.authenticateKey, (req, res) => {
  //add a brand new nation
  let nation = {
    _id: Date.now(),
    identify: req.physique.nation,
  };
  Nations.push(nation);
  res.standing(201).ship({
    knowledge: nation,
  });
});

app.hear(port, perform (err) {
  if (err) {
    console.error('Failure to launch server');
    return;
  }
  console.log(`Listening on port ${port}`);
});

Now, we’re accomplished with the coding a part of this tutorial, and we will transfer into testing. We’ll take a look at the API endpoints with cURL. Earlier than testing, open up your terminal and run the next command to start out the server:

npm run dev

Open one other terminal window and run the next command to create a brand new consumer. As soon as the command is run, you’ll be supplied with some consumer knowledge, one in every of which incorporates the API key:

curl -d "consumer:User1" -X POST http://127.0.0.1:4000/api/register -w "n"

Create New User API Key

Now that you’ve created a consumer, you should utilize the nation endpoints. Let’s attempt to retrieve the nations that we now have on the listing utilizing the API key that we have been supplied with. You are able to do so by working the command under. Ensure you substitute 2agp59nwu8nrszm4p6kfriekoeo0s1 within the command under with your personal API key:

curl http://127.0.0.1:4000/api/nation -H "x-api-key: 2agp59nwu8nrszm4p6kfriekoeo0s1" -w  "n"

Retrieve Country Endpoints

Conclusion

On this tutorial, we created an API with Node.js and developed an authentication system that generates an API key each time a consumer is registered. With the newly created API key, the consumer is ready to entry all of the routes on the API and API utilization may be tracked.

You may construct upon the data you could have obtained on this article by including API key authentication to your Node.js API that makes use of a database to retailer knowledge. Along with consumer authentication, you should utilize the API key for the benefits that have been talked about within the introductory part of this text.

200’s solely Monitor failed and gradual community requests in manufacturing

Deploying a Node-based net app or web site is the straightforward half. Ensuring your Node occasion continues to serve assets to your app is the place issues get more durable. In case you’re fascinated about making certain requests to the backend or third celebration providers are profitable, strive LogRocket. https://logrocket.com/signup/

LogRocket is sort of a DVR for net and cellular apps, recording actually all the pieces that occurs whereas a consumer interacts along with your app. As a substitute of guessing why issues occur, you’ll be able to mixture and report on problematic community requests to rapidly perceive the basis trigger.

LogRocket devices your app to file baseline efficiency timings corresponding to web page load time, time to first byte, gradual community requests, and likewise logs Redux, NgRx, and Vuex actions/state. .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments