Comprehensive Guide to Basic Authentication in cURL with NodeJS and SQLite

Comprehensive Guide to Basic Authentication in cURL with NodeJS and SQLite

In the world of web development, authentication is a crucial aspect that ensures secure communication between clients and servers. Basic Authentication is one of the simplest ways to enforce access control to web resources. This guide will walk you through implementing Basic Authentication using cURL, NodeJS, and SQLite. By the end of this article, you will have a solid understanding of how to set up and manage authentication in your applications.

Understanding Basic Authentication

Basic Authentication is a method for an HTTP user agent to provide a username and password when making a request. It is a simple authentication scheme built into the HTTP protocol. The client sends the credentials as a base64 encoded string in the HTTP header. While it is straightforward to implement, it is important to note that Basic Authentication is not secure over plain HTTP and should always be used with HTTPS to encrypt the credentials.

When a client requests access to a resource, the server responds with a 401 Unauthorized status code and a WWW-Authenticate header. The client then resends the request with the Authorization header containing the encoded credentials. This process is repeated for each request, as Basic Authentication does not maintain session state.

Setting Up NodeJS Environment

To get started, you need to have NodeJS and npm (Node Package Manager) installed on your machine. NodeJS is a JavaScript runtime built on Chrome’s V8 JavaScript engine, and npm is the default package manager for NodeJS. You can download and install NodeJS from the official website.

Once NodeJS is installed, you can create a new project directory and initialize it with npm. This will create a package.json file that will manage your project’s dependencies. Use the following commands to set up your project:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mkdir basic-authentication
cd basic-authentication
npm init -y
mkdir basic-authentication cd basic-authentication npm init -y
mkdir basic-authentication
cd basic-authentication
npm init -y

Next, you will need to install the necessary packages for your project. Express is a popular web framework for NodeJS, and you will use it to create a simple server. Additionally, you will need the sqlite3 package to interact with the SQLite database. Install these packages using npm:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install express sqlite3
npm install express sqlite3
npm install express sqlite3

Creating the SQLite Database

SQLite is a lightweight, serverless database engine that is perfect for small to medium-sized applications. It stores data in a single file, making it easy to manage and deploy. In this section, you will create a simple SQLite database to store user credentials.

First, create a new file named database.js in your project directory. This file will contain the code to set up and manage the SQLite database. Use the following script to create a database and a table for storing user credentials:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./users.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the users database.');
});
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
)`);
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Closed the database connection.');
});
const sqlite3 = require('sqlite3').verbose(); let db = new sqlite3.Database('./users.db', (err) => { if (err) { console.error(err.message); } console.log('Connected to the users database.'); }); db.serialize(() => { db.run(`CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL )`); }); db.close((err) => { if (err) { console.error(err.message); } console.log('Closed the database connection.'); });
const sqlite3 = require('sqlite3').verbose();

let db = new sqlite3.Database('./users.db', (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the users database.');
});

db.serialize(() => {
  db.run(`CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL,
    password TEXT NOT NULL
  )`);
});

db.close((err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Closed the database connection.');
});

This script creates a new SQLite database named users.db and a table named users with columns for id, username, and password. The id column is an auto-incrementing primary key, while the username and password columns store the user’s credentials.

Implementing Basic Authentication in NodeJS

With the database set up, you can now implement Basic Authentication in your NodeJS application. Create a new file named server.js in your project directory. This file will contain the code for your Express server and the authentication logic.

Start by importing the necessary modules and setting up the Express server:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const port = 3000;
app.use(express.json());
let db = new sqlite3.Database('./users.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the users database.');
});
const express = require('express'); const sqlite3 = require('sqlite3').verbose(); const app = express(); const port = 3000; app.use(express.json()); let db = new sqlite3.Database('./users.db', (err) => { if (err) { console.error(err.message); } console.log('Connected to the users database.'); });
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const port = 3000;

app.use(express.json());

let db = new sqlite3.Database('./users.db', (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the users database.');
});

Next, create a middleware function to handle Basic Authentication. This function will extract the credentials from the Authorization header, decode them, and verify them against the database:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function basicAuth(req, res, next) {
const authHeader = req.headers['authorization'];
if (!authHeader) {
res.setHeader('WWW-Authenticate', 'Basic');
return res.status(401).send('Authentication required.');
}
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
db.get('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], (err, row) => {
if (err) {
return res.status(500).send('Internal server error.');
}
if (!row) {
return res.status(401).send('Invalid credentials.');
}
next();
});
}
function basicAuth(req, res, next) { const authHeader = req.headers['authorization']; if (!authHeader) { res.setHeader('WWW-Authenticate', 'Basic'); return res.status(401).send('Authentication required.'); } const base64Credentials = authHeader.split(' ')[1]; const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii'); const [username, password] = credentials.split(':'); db.get('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], (err, row) => { if (err) { return res.status(500).send('Internal server error.'); } if (!row) { return res.status(401).send('Invalid credentials.'); } next(); }); }
function basicAuth(req, res, next) {
  const authHeader = req.headers['authorization'];
  if (!authHeader) {
    res.setHeader('WWW-Authenticate', 'Basic');
    return res.status(401).send('Authentication required.');
  }

  const base64Credentials = authHeader.split(' ')[1];
  const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
  const [username, password] = credentials.split(':');

  db.get('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], (err, row) => {
    if (err) {
      return res.status(500).send('Internal server error.');
    }
    if (!row) {
      return res.status(401).send('Invalid credentials.');
    }
    next();
  });
}

This middleware function checks for the presence of the Authorization header, decodes the credentials, and queries the database to verify them. If the credentials are valid, the request is passed to the next middleware or route handler; otherwise, an error response is sent.

Finally, create a protected route that requires authentication. Use the basicAuth middleware to protect this route:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app.get('/protected', basicAuth, (req, res) => {
res.send('This is a protected resource.');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
app.get('/protected', basicAuth, (req, res) => { res.send('This is a protected resource.'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
app.get('/protected', basicAuth, (req, res) => {
  res.send('This is a protected resource.');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

With this setup, any request to the /protected route will require valid credentials. If the credentials are missing or incorrect, the server will respond with a 401 Unauthorized status code.

Testing Basic Authentication with cURL

cURL is a command-line tool for transferring data with URLs

Responses

Related blogs

an introduction to web scraping with NodeJS and Firebase. A futuristic display showcases NodeJS code extrac
parsing XML using Ruby and Firebase. A high-tech display showcases Ruby code parsing XML data structure
handling timeouts in Python Requests with Firebase. A high-tech display showcases Python code implement
downloading a file with cURL in Ruby and Firebase. A high-tech display showcases Ruby code using cURL t