NodeJs Series (Part#3) — Basic Authentication.
In the Previous Article we have created the simple CRDU RESTful Apis using ExpressJS. Lets explore the Basic Authentication in Node.js.
Get Zeeshan Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
Basic Authentication can be implemented by manually checking the credentials in the request headers. Here’s how you can add Basic Authentication to your Node.js app using the Express framework.
Step 1: Create Basic Authentication Middleware
- Open the app.js file of your my-app project.
- Create a middleware to check the
Authorizationheader for valid credentials. TheAuthorizationheader in Basic Authentication contains a base64-encoded string in the format.
Step 2: Set Up the API with Basic Authentication
- Basic Authentication Middleware:
The middlewarebasicAuthextracts theAuthorizationheader from the request. It checks if the header is in the correct format (Basic <base64-encoded-username:password>), decodes the base64 string, and compares the username and password with the expected values. If the credentials are correct, it callsnext()to allow the request to proceed to the route handler. - Protected Route:
The route/api/secure-datais protected by Basic Authentication, meaning it can only be accessed if the request contains valid credentials in theAuthorizationheader.
Add the following code in to the app.js file.
function basicAuth(req, res, next) {
const authHeader = req.headers['authorization'];
if (!authHeader) {
return res.status(401).json({ message: 'No authorization header provided' });
}
const [scheme, credentials] = authHeader.split(' ');
if (scheme !== 'Basic' || !credentials) {
return res.status(401).json({ message: 'Invalid authorization format' });
}
const decoded = Buffer.from(credentials, 'base64').toString('utf-8');
const [username, password] = decoded.split(':');
// Set your own username and password
const validUsername = 'user';
const validPassword = 'password';
if (username === validUsername && password === validPassword) {
next(); // Authentication passed, proceed to the route
} else {
return res.status(403).json({ message: 'Forbidden: Invalid credentials' });
}
}Step 3: Set Up the API with Basic Authentication
Add the following route to the app.js file.
app.get('/api/secure-data', basicAuth, (req, res) => {
res.json({ message: 'This is a protected route, accessible only with valid credentials!' });
});your code should look like this.
Step 4: Run the Server
node app.jsStep 5: Testing the API
Using Postman:
- Open Postman.
- Select the method as GET and enter the URL
http://localhost:3000/api/secure-data. - Under the Authorization tab, select Basic Auth.
- Enter the username (
user) and password (password). - Send the request, and you should receive a response
{ "message": "This is a protected route, accessible only with valid credentials!" }






