Installations
npm install @fastify/basic-auth
Developer
fastify
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
20.8.0
NPM Version
10.1.0
Statistics
76 Stars
163 Commits
25 Forks
17 Watching
2 Branches
31 Contributors
Updated on 21 Nov 2024
Languages
JavaScript (94.8%)
TypeScript (5.2%)
Total Downloads
Cumulative downloads
Total Downloads
6,821,319
Last day
-18.3%
10,056
Compared to previous day
Last week
16.9%
70,115
Compared to previous week
Last month
-3.5%
276,891
Compared to previous month
Last year
715.3%
5,945,362
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Dev Dependencies
7
@fastify/basic-auth
A simple basic auth plugin for Fastify.
Install
npm i @fastify/basic-auth
Usage
This plugin decorates the fastify instance with a basicAuth
function, which you can use inside any hook before your route handler, or with @fastify/auth
.
1const fastify = require('fastify')() 2const authenticate = {realm: 'Westeros'} 3fastify.register(require('@fastify/basic-auth'), { validate, authenticate }) 4// `this` inside validate is `fastify` 5function validate (username, password, req, reply, done) { 6 if (username === 'Tyrion' && password === 'wine') { 7 done() 8 } else { 9 done(new Error('Winter is coming')) 10 } 11} 12 13fastify.after(() => { 14 fastify.addHook('onRequest', fastify.basicAuth) 15 16 fastify.get('/', (req, reply) => { 17 reply.send({ hello: 'world' }) 18 }) 19})
Promises and async/await are supported as well!
1const fastify = require('fastify')() 2const authenticate = {realm: 'Westeros'} 3fastify.register(require('@fastify/basic-auth'), { validate, authenticate }) 4async function validate (username, password, req, reply) { 5 if (username !== 'Tyrion' || password !== 'wine') { 6 return new Error('Winter is coming') 7 } 8}
Use with onRequest
:
1const fastify = require('fastify')() 2const authenticate = {realm: 'Westeros'} 3fastify.register(require('@fastify/basic-auth'), { validate, authenticate }) 4async function validate (username, password, req, reply) { 5 if (username !== 'Tyrion' || password !== 'wine') { 6 return new Error('Winter is coming') 7 } 8} 9 10fastify.after(() => { 11 fastify.route({ 12 method: 'GET', 13 url: '/', 14 onRequest: fastify.basicAuth, 15 handler: async (req, reply) => { 16 return { hello: 'world' } 17 } 18 }) 19})
Use with @fastify/auth
:
1const fastify = require('fastify')() 2const authenticate = {realm: 'Westeros'} 3fastify.register(require('@fastify/auth')) 4fastify.register(require('@fastify/basic-auth'), { validate, authenticate }) 5async function validate (username, password, req, reply) { 6 if (username !== 'Tyrion' || password !== 'wine') { 7 return new Error('Winter is coming') 8 } 9} 10 11fastify.after(() => { 12 // use preHandler to authenticate all the routes 13 fastify.addHook('preHandler', fastify.auth([fastify.basicAuth])) 14 15 fastify.route({ 16 method: 'GET', 17 url: '/', 18 // use onRequest to authenticate just this one 19 onRequest: fastify.auth([fastify.basicAuth]), 20 handler: async (req, reply) => { 21 return { hello: 'world' } 22 } 23 }) 24})
Custom error handler
On failed authentication, @fastify/basic-auth will call the Fastify
generic error
handler with an error.
@fastify/basic-auth sets the err.statusCode
property to 401
.
In order to properly 401
 errors:
1fastify.setErrorHandler(function (err, req, reply) { 2 if (err.statusCode === 401) { 3 // this was unauthorized! Display the correct page/message. 4 reply.code(401).send({ was: 'unauthorized' }) 5 return 6 } 7 reply.send(err) 8})
Options
utf8
(optional, default: true)
User-ids or passwords containing characters outside the US-ASCII character set will cause interoperability issues, unless both communication partners agree on what character encoding scheme is to be used. If utf8 is set to true the server will send the 'charset' parameter to indicate a preference of "UTF-8", increasing the probability that clients will switch to that encoding.
strictCredentials
(optional, default: true)
If strictCredentials is set to false the authorization header can contain
additional whitespaces at the beginning, in the midde and at the end of the
authorization header.
This is a fallback option to ensure the same behaviour as @fastify/basic-auth
version <=5.x.
validate
(required)
The validate
function is called on each request made,
and is passed the username
, password
, req
and reply
parameters in that order. An optional fifth parameter, done
may be
used to signify a valid request when called with no arguments,
or an invalid request when called with an Error
object. Alternatively,
the validate
function may return a promise, resolving for valid
requests and rejecting for invalid. This can also be achieved using
an async/await
function, and throwing for invalid requests.
See code above for examples.
authenticate
<Boolean|Object> (optional, default: false)
When supplied, the authenticate
option will cause the
WWW-Authenticate
header to be added. It may also be used to set the realm
value.
This can be useful in situations where we want to trigger client-side authentication interfaces - for instance the browser authentication dialog.
As a boolean setting authenticate
to true
will set a header like so: WWW-Authenticate: Basic
. When false
, no header is added. This is the default.
1fastify.register(require('@fastify/basic-auth'), { 2 validate, 3 authenticate: true // WWW-Authenticate: Basic 4}) 5 6fastify.register(require('@fastify/basic-auth'), { 7 validate, 8 authenticate: false // no authenticate header, same as omitting authenticate option 9})
When supplied as an object the authenticate
option may have a realm
key.
If the realm
key is supplied, it will be appended to the header value:
1fastify.register(require('@fastify/basic-auth'), { 2 validate, 3 authenticate: {realm: 'example'} // WWW-Authenticate: Basic realm="example" 4})
The realm
key could also be a function:
1fastify.register(require('@fastify/basic-auth'), { 2 validate, 3 authenticate: { 4 realm(req) { 5 return 'example' // WWW-Authenticate: Basic realm="example" 6 } 7 } 8})
header
String (optional)
When supplied, the header option is the name of the header to get credentials from for validation.
1fastify.register(require('@fastify/basic-auth'), { 2 validate, 3 header: 'x-forwarded-authorization' 4})
License
Licensed under MIT.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
security policy file detected
Details
- Info: security policy file detected: github.com/fastify/.github/SECURITY.md:1
- Info: Found linked content: github.com/fastify/.github/SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: github.com/fastify/.github/SECURITY.md:1
- Info: Found text in security policy: github.com/fastify/.github/SECURITY.md:1
Reason
SAST tool is not run on all commits -- score normalized to 8
Details
- Warn: 20 commits out of 23 are checked with a SAST tool
Reason
7 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 5
Reason
Found 11/21 approved changesets -- score normalized to 5
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Score
6.5
/10
Last Scanned on 2024-11-25
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