Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
express-basic-auth
Advanced tools
The express-basic-auth npm package is a simple and straightforward middleware for adding basic HTTP authentication to an Express.js application. It allows you to protect routes with a username and password, making it useful for securing endpoints in a lightweight manner.
Basic Authentication
This feature allows you to set up basic authentication for your Express.js routes. In this example, the middleware is configured to require a username 'admin' and password 'supersecret' to access the root route.
const express = require('express');
const basicAuth = require('express-basic-auth');
const app = express();
app.use(basicAuth({
users: { 'admin': 'supersecret' },
challenge: true
}));
app.get('/', (req, res) => {
res.send('Hello, authenticated user!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Custom Unauthorized Response
This feature allows you to customize the response sent to clients when they fail to authenticate. In this example, the middleware is configured to return a simple 'Unauthorized' message.
const express = require('express');
const basicAuth = require('express-basic-auth');
const app = express();
app.use(basicAuth({
users: { 'admin': 'supersecret' },
unauthorizedResponse: (req) => 'Unauthorized'
}));
app.get('/', (req, res) => {
res.send('Hello, authenticated user!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Custom Authentication Function
This feature allows you to define a custom function to handle authentication logic. In this example, the custom authorizer function checks if the provided username and password match the expected values using a timing-safe comparison.
const express = require('express');
const basicAuth = require('express-basic-auth');
const app = express();
app.use(basicAuth({
authorizer: (username, password) => {
const userMatches = basicAuth.safeCompare(username, 'admin');
const passwordMatches = basicAuth.safeCompare(password, 'supersecret');
return userMatches & passwordMatches;
},
authorizeAsync: false,
challenge: true
}));
app.get('/', (req, res) => {
res.send('Hello, authenticated user!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
The http-auth package provides a more comprehensive set of authentication strategies, including basic and digest access authentication. It is more flexible and supports a wider range of use cases compared to express-basic-auth.
The passport-http package is a strategy for the Passport authentication middleware that supports HTTP Basic and Digest authentication. It integrates with the Passport ecosystem, allowing for more complex authentication flows and combining multiple strategies.
The express-jwt package is used for securing Express.js routes using JSON Web Tokens (JWT). While it provides a different type of authentication compared to basic auth, it is a popular choice for more secure and scalable authentication mechanisms.
Simple plug & play HTTP basic auth middleware for Express.
Just run
npm install express-basic-auth
add the --save
option to add it to the dependencies
in your package.json
as well
The module will export a function, that you can call with an options object to get the middleware:
var app = require('express')()
var basicAuth = require('express-basic-auth')
app.use(basicAuth({
users: { 'admin': 'supersecret' }
}))
The middleware will now check incoming requests to match the credentials
admin:supersecret
.
The middleware will check incoming requests for a basic auth (Authorization
)
header, parse it and check if the credentials are legit. If there are any
credentials, an auth
property will be added to the request, containing
an object with user
and password
properties, filled with the credentials,
no matter if they are legit or not.
If a request is found to not be authorized, it will respond with HTTP 401 and a configurable body (default empty).
If you simply want to check basic auth against one or multiple static credentials,
you can pass those credentials in the users
option:
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl'
}
}))
The middleware will check incoming requests to have a basic auth header matching one of the three passed credentials.
Alternatively, you can pass your own authorizer
function, to check the credentials
however you want. It will be called with a username and password and is expected to
return true
or false
to indicate that the credentials were approved or not:
app.use(basicAuth( { authorizer: myAuthorizer } ))
function myAuthorizer(username, password) {
return username.startsWith('A') && password.startsWith('secret')
}
This will authorize all requests with credentials where the username begins with
'A'
and the password begins with 'secret'
. In an actual application you would
likely look up some data instead ;-)
Note that the authorizer
function above is expected to be synchronous. This is
the default behavior, you can pass authorizeAsync: true
in the options object to indicate
that your authorizer is asynchronous. In this case it will be passed a callback
as the third parameter, which is expected to be called by standard node convention
with an error and a boolean to indicate if the credentials have been approved or not.
Let's look at the same authorizer again, but this time asynchronous:
app.use(basicAuth({
authorizer: myAsyncAuthorizer,
authorizeAsync: true
}))
function myAsyncAuthorizer(username, password, cb) {
if(username.startsWith('A') && password.startsWith('secret'))
return cb(null, true)
else
return cb(null, false)
}
Per default, the response body for unauthorized responses will be empty. It can
be configured using the unauthorizedResponse
option. You can either pass a
static response or a function that gets passed the express request object and is
expected to return the response body. If the response body is a string, it will
be used as-is, otherwise it will be sent as JSON:
app.use(basicAuth({
users: { 'Foo': 'bar' },
unauthorizedResponse: getUnauthorizedResponse
}))
function getUnauthorizedResponse(req) {
return req.auth ?
('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected') :
'No credentials provided'
}
Per default the middleware will not add a WWW-Authenticate
challenge header to
responses of unauthorized requests. You can enable that by adding challenge: true
to the options object. This will cause most browsers to show a popup to enter
credentials on unauthorized responses. You can set the realm (the realm
identifies the system to authenticate against and can be used by clients to save
credentials) of the challenge by passing a static string or a function that gets
passed the request object and is expected to return the challenge:
app.use(basicAuth({
users: { 'someuser': 'somepassword' },
challenge: true,
realm: 'Imb4T3st4pp'
}))
The repository contains an example.js
that you can run to play around and try
the middleware. To use it just put it somewhere (or leave it where it is), run
npm install express express-basic-auth
node example.js
This will start a small express server listening at port 8080. Just look at the file, try out the requests and play around with the options.
The cases in the example.js
are also used for automated testing. So if you want
to contribute or just make sure that the package still works, simply run:
npm test
FAQs
Plug & play basic auth middleware for express
The npm package express-basic-auth receives a total of 435,708 weekly downloads. As such, express-basic-auth popularity was classified as popular.
We found that express-basic-auth demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.