3 [![NPM Version][npm-image]][npm-url]
4 [![NPM Downloads][downloads-image]][downloads-url]
5 [![Node.js Version][node-version-image]][node-version-url]
6 [![Build Status][travis-image]][travis-url]
7 [![Test Coverage][coveralls-image]][coveralls-url]
9 Generic basic auth Authorization header field parser for whatever.
13 This is a [Node.js](https://nodejs.org/en/) module available through the
14 [npm registry](https://www.npmjs.com/). Installation is done using the
15 [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
18 $ npm install basic-auth
23 <!-- eslint-disable no-unused-vars -->
26 var auth = require('basic-auth')
31 Get the basic auth credentials from the given request. The `Authorization`
32 header is parsed and if the header is invalid, `undefined` is returned,
33 otherwise an object with `name` and `pass` properties.
35 ### auth.parse(string)
37 Parse a basic auth authorization header string. This will return an object
38 with `name` and `pass` properties, or `undefined` if the string is invalid.
42 Pass a Node.js request object to the module export. If parsing fails
43 `undefined` is returned, otherwise an object with `.name` and `.pass`.
45 <!-- eslint-disable no-unused-vars, no-undef -->
48 var auth = require('basic-auth')
50 // => { name: 'something', pass: 'whatever' }
53 A header string from any other location can also be parsed with
54 `auth.parse`, for example a `Proxy-Authorization` header:
56 <!-- eslint-disable no-unused-vars, no-undef -->
59 var auth = require('basic-auth')
60 var user = auth.parse(req.getHeader('Proxy-Authorization'))
63 ### With vanilla node.js http server
66 var http = require('http')
67 var auth = require('basic-auth')
68 var compare = require('tsscmp')
71 var server = http.createServer(function (req, res) {
72 var credentials = auth(req)
75 // The "check" function will typically be against your user store
76 if (!credentials || !check(credentials.name, credentials.pass)) {
78 res.setHeader('WWW-Authenticate', 'Basic realm="example"')
79 res.end('Access denied')
81 res.end('Access granted')
85 // Basic function to validate credentials for example
86 function check (name, pass) {
89 // Simple method to prevent short-circut and use timing-safe compare
90 valid = compare(name, 'john') && valid
91 valid = compare(pass, 'secret') && valid
104 [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/basic-auth/master
105 [coveralls-url]: https://coveralls.io/r/jshttp/basic-auth?branch=master
106 [downloads-image]: https://badgen.net/npm/dm/basic-auth
107 [downloads-url]: https://npmjs.org/package/basic-auth
108 [node-version-image]: https://badgen.net/npm/node/basic-auth
109 [node-version-url]: https://nodejs.org/en/download
110 [npm-image]: https://badgen.net/npm/v/basic-auth
111 [npm-url]: https://npmjs.org/package/basic-auth
112 [travis-image]: https://badgen.net/travis/jshttp/basic-auth/master
113 [travis-url]: https://travis-ci.org/jshttp/basic-auth