Parse Basic Auth Credentials
This code demonstrates how to use basic-auth to parse the `Authorization` header in an Express.js application. It checks if the credentials match a predefined username and password, and either grants access or denies it with a 401 status code.
const auth = require('basic-auth');
const express = require('express');
const app = express();
app.use((req, res) => {
const credentials = auth(req);
if (!credentials || credentials.name !== 'user' || credentials.pass !== 'pass') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="example"');
res.end('Access denied');
} else {
res.end('Access granted');
}
});
app.listen(3000);