Skip to main content

Command Palette

Search for a command to run...

API Authentication using code

Published
•6 min read
API Authentication using code
K

I am a Front-End Developer, Open Source Contribution.

What we will be doing?

As you can see on the above web page. Now as soon as you click on

  1. No Auth:- You will get to see the random secret

  2. Basic Auth:- You will get all path

  3. API Key:- You will get the filtered Endpoints

  4. Token:- You will get a secret with a particular ID.

Let's start to make the applicationšŸ™Œ

  1. Install required package

npm install
npm i nodemon
npm i express
npm i axios
  1. File Structure

Make a file name index.js. Now, make a new folder named views, now inside the views make a file named index.ejs.

The file structure is as follows

  1. Make a server inside index.js

// index.js

import express from "express";

const app = express();
const port = 3000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Now, inside the terminal write the below line to start the server

nodemon index.js
  1. Now make the frontend and send it to the server

<!--index.ejs-->

<!DOCTYPE html>
<html>

<head>
  <title>API Authentication</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100vh;
      font-family: Arial, sans-serif;
      background-color: #f0f0f0;
    }

    button {
      margin: 10px;
      padding: 15px 30px;
      font-size: 16px;
      border: none;
      border-radius: 5px;
      color: white;
      cursor: pointer;
    }

    #noAuth {
      background-color: #3498db;
    }

    #basicAuth {
      background-color: #2ecc71;
    }

    #apiKey {
      background-color: #f1c40f;
    }

    #token {
      background-color: #e74c3c;
    }

    .response-area {
      margin-top: 20px;
      background-color: white;
      padding: 20px;
    }
  </style>
</head>

<body>
  <button type="submit" id="noAuth">No Auth</button>
  <button id="basicAuth">Basic Auth</button>
  <button id="apiKey">API Key</button>
  <button id="token">Token</button>
</body>
</html>

Now inside index.js

//index.js

app.get("/", (req, res) => {
  res.render("index.ejs", { content: "API Response." });
});

After performing above step you will see the below web page

  1. Now we will store the values of API URL, Username, Password, APIKey, and Token inside index.js

const APIURL = "https://secrets-api.appbrewery.com";

// TODO: Replace the values below with your own before running this file.
const Username = "HetashriK";
const Password = "HK";
const APIKey = "b65f2150-6375-4e29-baad-016abaa00914";
const Token = "d0972a43-aa27-4cf3-9f94-9ed56acad04d";
  1. Now we will manipulate No Auth

app.get("/noAuth", async (req, res) => {
  try {

    //We have used axios to make get request to the URL at random endpoint and get the data
    const result = await axios.get(APIURL + "/random");

    //Once we get the data we will pass it to index.ejs as a simple string
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

Now in index.ejs we will provide onclick attribute in No Auth and also pass content in EJS Special Tags


<!--Here window.location.href is an Javascript property which represent URL of the current page-->
<!--/noAuth representing URL Path-->
<button type="submit" id="noAuth" onclick="window.location.href='/noAuth'">No Auth</button>
 <div class="response-area">
    <p>
      <%=content%>
    </p>
  </div>
  1. Now we will manipulate Basic Auth

app.get("/basicAuth", async (req, res) => {
  try {

     //We have used axios to make get request to the URL at the given endpoint, pass the parameter as username and password and get the data
    const result = await axios.get(APIURL + "/all?page=2",
      {
        auth: {
          username: Username,
          password: Password,
        },
      }
    );

    //Once we get the data we will pass it to index.ejs as a simple string
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

Now in index.ejs we will provide onclick attribute in Basic Auth


<!--Here window.location.href is an Javascript property which represent URL of the current page-->
<!--/basicAuth representing URL Path-->
<button id="basicAuth" onclick="window.location.href='/basicAuth'">Basic Auth</button>
  1. Now we will manipulate API Key

app.get("/basicAuth", async (req, res) => {
  try {

     //We have used axios to make get request to the URL at the given endpoint, pass the parameter as score and APIKEY and get the data
    const result = await axios.get(API_URL + "/filter", {
      params: {
        score: 5,
        apiKey: APIKey,
      },
    });

    //Once we get the data we will pass it to index.ejs as a simple string
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

Now in index.ejs we will provide onclick attribute in API Key


<!--Here window.location.href is an Javascript property which represent URL of the current page-->
<!--/apiKey representing URL Path-->
<button id="apiKey" onclick="window.location.href='/apiKey'">API Key</button>
  1. Now we will manipulate Token


//We are providing header as parameter
const config = {
  headers: { Authorization: `Bearer ${Token}` },
};

app.get("/token", async (req, res) => {
  try {

    //We have used axios to make get request to the URL at the given endpoint, pass the parameter as token as header and get the data
    const result = await axios.get(APIURL + "/secrets/1", config);

    //Once we get the data we will pass it to index.ejs as a simple string
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

Now in index.ejs we will provide onclick attribute in Token


<!--Here window.location.href is an Javascript property which represent URL of the current page-->
<!--/token representing URL Path-->
<button id="token" onclick="window.location.href='/token'">Token</button>

Whole Code

<!--index.ejs-->

<!DOCTYPE html>
<html>

<head>
  <title>API Authentication</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100vh;
      font-family: Arial, sans-serif;
      background-color: #f0f0f0;
    }

    button {
      margin: 10px;
      padding: 15px 30px;
      font-size: 16px;
      border: none;
      border-radius: 5px;
      color: white;
      cursor: pointer;
    }

    #noAuth {
      background-color: #3498db;
    }

    #basicAuth {
      background-color: #2ecc71;
    }

    #apiKey {
      background-color: #f1c40f;
    }

    #token {
      background-color: #e74c3c;
    }

    .response-area {
      margin-top: 20px;
      background-color: white;
      padding: 20px;
    }
  </style>
</head>

<body>
  <button type="submit" id="noAuth" onclick="window.location.href='/noAuth'">No Auth</button>
  <button id="basicAuth" onclick="window.location.href='/basicAuth'">Basic Auth</button>
  <button id="apiKey" onclick="window.location.href='/apiKey'">API Key</button>
  <button id="token" onclick="window.location.href='/token'">Token</button>

  <div class="response-area">
    <p>
      <%=content%>
    </p>
  </div>
</body>

</html>
//index.js

import express from "express";
import axios from "axios";

const app = express();
const port = 3000;
const APIURL = "https://secrets-api.appbrewery.com";

// TODO: Replace the values below with your own before running this file.
const Username = "HetashriK";
const Password = "HK";
const APIKey = "b65f2150-6375-4e29-baad-016abaa00914";
const Token = "d0972a43-aa27-4cf3-9f94-9ed56acad04d";

app.get("/", (req, res) => {
  res.render("index.ejs", { content: "API Response." });
});

app.get("/noAuth", async (req, res) => {
  try {
    const result = await axios.get(APIURL + "/random");
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

app.get("/basicAuth", async (req, res) => {
  try {
    const result = await axios.get(APIURL + "/all?page=2",
      {
        auth: {
          username: Username,
          password: Password,
        },
      }
    );
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

app.get("/apiKey", async (req, res) => {
  try {
    const result = await axios.get(APIURL + "/filter", {
      params: {
        score: 5,
        apiKey: APIKey,
      },
    });
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

const config = {
  headers: { Authorization: `Bearer ${Token}` },
};

app.get("/token", async (req, res) => {
  try {
    const result = await axios.get(APIURL + "/secrets/1", config);
    res.render("index.ejs", { content: JSON.stringify(result.data) });
  } catch (error) {
    res.status(404).send("Error:", error.message);
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

OUTPUT

  1. When you hit No Auth

  2. When you hit Basic Auth

  3. When you hit API Key

  4. When you hit Token

Source

https://github.com/hetashridk/API-Authentication

Conclusion

In this article, we have seen that using Axios we can easily get requests to another server and retrieve data by using a username, password, API key and token.