Written by Sümeyye Sever (notes I took while creating web development projects)
API authentication is the process of verifying the identity of a user who is making an API request, and it is a crucial pillar of API security. There are many types of API authentication, such as HTTP basic authentication, API key authentication, JWT, and OAuth, and each one has its own benefits, trade-offs, and ideal use cases. Nevertheless, all API authentication mechanisms share the goal of protecting sensitive data and ensuring the API is not misused.
There are many API authentication mechanisms, and each one operates differently. These four methods are among the most common:
HTTP basic authentication is the most rudimentary way to implement API authentication. It involves sending credentials as user/password pairs in an Authorization header field, where the credentials are encoded using Base64. However, these credentials are not hashed or encrypted, which makes this authentication mechanism insecure unless it is used in conjunction with HTTPS.
Server-Side: Using Node.js with Express (index.js)
import express from "express"
const app = express();
// Dummy credentials
const VALID_USERNAME = 'admin';
const VALID_PASSWORD = 'password123';
// Middleware for Basic Authentication
const basicAuth = (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader) {
res.setHeader('WWW-Authenticate', 'Basic realm="Login Required"');
return res.status(401).json({ message: 'Authentication required' });
}
// Extract and decode credentials
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('utf8');
const [username, password] = credentials.split(':');
// Verify credentials
if (username === VALID_USERNAME && password === VALID_PASSWORD) {
return next(); // Authentication successful
}
res.status(401).json({ message: 'Invalid credentials' });
};
app.get('/secure-data', basicAuth, (req, res) => {
res.json({ message: 'You have access to secure data!' });
});
app.listen(3000, () => {
console.log('Server running on <http://localhost:3000>');
});
const basicAuth = (req, res, next) => {
The function takes three arguments:
req: The incoming request object.res: The response object.next: A callback function to pass control to the next middleware or route handler if authentication succeeds.const authHeader = req.headers['authorization'];