Installations
npm install express-basic-auth-safe
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
8.7.0
NPM Version
5.7.1
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
Developer
LionC
Download Statistics
Total Downloads
2,635
Last Day
1
Last Week
2
Last Month
9
Last Year
219
GitHub Statistics
331 Stars
73 Commits
56 Forks
2 Watching
5 Branches
2 Contributors
Bundle Size
1.86 kB
Minified
896.00 B
Minified + Gzipped
Package Meta Information
Latest Version
1.1.4
Package Id
express-basic-auth-safe@1.1.4
Size
5.95 kB
NPM Version
5.7.1
Node Version
8.7.0
Publised On
12 Mar 2018
Total Downloads
Cumulative downloads
Total Downloads
2,635
Last day
0%
1
Compared to previous day
Last week
100%
2
Compared to previous week
Last month
-10%
9
Compared to previous month
Last year
26.6%
219
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
6
express-basic-auth
Simple plug & play HTTP basic auth middleware for Express.
How to install
Just run
1npm install express-basic-auth
How to use
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).
Static Users
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.
Custom authorization
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:
1app.use(basicAuth( { authorizer: myAuthorizer } ))
2
3function myAuthorizer(username, password) {
4 return username.startsWith('A') && password.startsWith('secret')
5}
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 ;-)
Custom Async Authorization
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}
Unauthorized Response Body
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}
Challenge
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}))
Try it
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.
TypeScript usage
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})
Tests
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
![Empty State](/_next/static/media/empty.e5fae2e5.png)
No vulnerabilities found.
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
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
license file not detected
Details
- Warn: project does not have a license file
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 5 are checked with a SAST tool
Reason
15 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-h452-7996-h45h
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-rv95-896h-c2vc
- Warn: Project is vulnerable to: GHSA-qw6h-vgh9-j6wx
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-qrpm-p2h7-hrv2
- Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-rhx6-c78j-4q9w
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
Score
1.6
/10
Last Scanned on 2025-01-27
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 More