basic-auth
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
safe-buffer | 5.1.2 | 9.59 kB | MIT | prod |
Basic-auth is a popular Node.js module that serves as a generic parser for basic auth Authorization header fields. This means the module provides a simple way to retrieve and parse the credentials from a basic auth header. If the header is invalid, it returns undefined
. If valid, it returns an object containing name
and pass
properties.
You can easily utilize basic-auth in your project by first installing it from the npm registry with the command $ npm install basic-auth
.
After the installation, you can require it in your JavaScript file like this:
var auth = require('basic-auth');
Here is an example of how to use basic-auth to get basic auth credentials from a given request:
var auth = require('basic-auth')
var user = auth(req)
// => { name: 'something', pass: 'whatever' }
Additionally, you can parse a header string from any location with auth.parse
:
var auth = require('basic-auth');
var user = auth.parse(req.getHeader('Proxy-Authorization'));
Here's how you might use basic-auth with a vanilla Node.js HTTP server:
var http = require('http')
var auth = require('basic-auth')
var compare = require('tsscmp')
// Create server
var server = http.createServer(function (req, res) {
var credentials = auth(req)
// Check credentials
// The "check" function will typically be against your user store
if (!credentials || !check(credentials.name, credentials.pass)) {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="example"')
res.end('Access denied')
} else {
res.end('Access granted')
}
})
// Basic function to validate credentials for example
function check (name, pass) {
var valid = true
// Simple method to prevent short-circut and use timing-safe compare
valid = compare(name, 'john') && valid
valid = compare(pass, 'secret') && valid
return valid
}
// Listen
server.listen(3000)
The current basic-auth documentation is found within the README file of the package's GitHub repository, located at https://github.com/jshttp/basic-auth. The documentation features instructions for installation, brief descriptions of the API, and a few example usage scenarios.