Gathering detailed insights and metrics for express-basic-auth
Gathering detailed insights and metrics for express-basic-auth
Gathering detailed insights and metrics for express-basic-auth
Gathering detailed insights and metrics for express-basic-auth
Plug & play basic auth middleware for express
npm install express-basic-auth
Typescript
Module System
Node Version
NPM Version
99.6
Supply Chain
100
Quality
76
Maintenance
100
Vulnerability
100
License
JavaScript (100%)
Total Downloads
77,055,749
Last Day
81,831
Last Week
373,456
Last Month
1,713,480
Last Year
22,342,799
331 Stars
73 Commits
56 Forks
2 Watching
5 Branches
2 Contributors
Minified
Minified + Gzipped
Latest Version
1.2.1
Package Id
express-basic-auth@1.2.1
Unpacked Size
30.60 kB
Size
7.18 kB
File Count
7
NPM Version
8.2.0
Node Version
17.2.0
Publised On
11 Dec 2021
Cumulative downloads
Total Downloads
Last day
-10%
81,831
Compared to previous day
Last week
-18.3%
373,456
Compared to previous week
Last month
2.2%
1,713,480
Compared to previous month
Last year
13.4%
22,342,799
Compared to previous year
1
6
Simple plug & play HTTP basic auth middleware for Express.
Just run
1npm install express-basic-auth
The module will export a function, that you can call with an options object to get the middleware:
1const app = require('express')() 2const basicAuth = require('express-basic-auth') 3 4app.use(basicAuth({ 5 users: { 'admin': 'supersecret' } 6}))
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:
1app.use(basicAuth({ 2 users: { 3 'admin': 'supersecret', 4 'adam': 'password1234', 5 'eve': 'asdfghjkl', 6 } 7}))
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.
When using your own authorizer
, make sure not to use standard string comparison (==
/ ===
)
when comparing user input with secret credentials, as that would make you vulnerable against
timing attacks. Use the provided safeCompare
function instead - always provide the user input as its first argument. Also make sure to use bitwise
logic operators (|
and &
) instead of the standard ones (||
and &&
) for the same reason, as
the standard ones use shortcuts.
1app.use(basicAuth( { authorizer: myAuthorizer } ))
2
3function myAuthorizer(username, password) {
4 const userMatches = basicAuth.safeCompare(username, 'customuser')
5 const passwordMatches = basicAuth.safeCompare(password, 'custompassword')
6
7 return userMatches & passwordMatches
8}
This will authorize all requests with the credentials 'customuser:custompassword'.
In an actual application you would likely look up some data instead ;-) You can do whatever you
want in custom authorizers, just return true
or false
in the end and stay aware of timing
attacks.
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:
1app.use(basicAuth({ 2 authorizer: myAsyncAuthorizer, 3 authorizeAsync: true, 4})) 5 6function myAsyncAuthorizer(username, password, cb) { 7 if (username.startsWith('A') & password.startsWith('secret')) 8 return cb(null, true) 9 else 10 return cb(null, false) 11}
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:
1app.use(basicAuth({ 2 users: { 'Foo': 'bar' }, 3 unauthorizedResponse: getUnauthorizedResponse 4})) 5 6function getUnauthorizedResponse(req) { 7 return req.auth 8 ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected') 9 : 'No credentials provided' 10}
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:
1app.use(basicAuth({ 2 users: { 'someuser': 'somepassword' }, 3 challenge: true, 4 realm: 'Imb4T3st4pp', 5}))
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
1npm install express express-basic-auth 2node 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.
A declaration file is bundled with the library. You don't have to install a @types/
package.
1import * as basicAuth from 'express-basic-auth'
:bulb: Using req.auth
express-basic-auth sets req.auth
to an object containing the authorized credentials like { user: 'admin', password: 'supersecret' }
.
In order to use that req.auth
property in TypeScript without an unknown property error, use covariance to downcast the request type:
1app.use(basicAuth(options), (req: basicAuth.IBasicAuthedRequest, res, next) => { 2 res.end(`Welcome ${req.auth.user} (your password is ${req.auth.password})`) 3 next() 4})
:bulb: A note about type inference on synchronous authorizers
Due to some TypeScript's type-system limitation, the arguments' type of the synchronous authorizers are not inferred. For example, on an asynchronous authorizer, the three arguments are correctly inferred:
1basicAuth({ 2 authorizeAsync: true, 3 authorizer: (user, password, authorize) => authorize(null, password == 'secret'), 4})
However, on a synchronous authorizer, you'll have to type the arguments yourself:
1basicAuth({ 2 authorizer: (user: string, password: string) => (password == 'secret') 3})
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:
1npm test
Stable Version
1
3.1/10
Summary
express-basic-auth Timing Attack due to native string comparison instead of constant time string comparison
Affected Versions
< 1.1.7
Patched Versions
1.1.7
Reason
no binaries found in the repo
Reason
Found 3/30 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
license file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
15 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-02-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Moreexpress-rate-limit
Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
auth-header
For HTTP `Authorization` and `WWW-Authenticate` headers.
express-basic-auth-safe
Plug & play basic auth middleware for express
rupyy-express-basic-auth
Plug & play basic auth middleware for express