Skip to content

Generic basic auth Authorization header field parser

License

Notifications You must be signed in to change notification settings

jshttp/basic-auth

Repository files navigation

basic-auth

NPM VersionNPM DownloadsNode.js VersionBuild StatusCoverage Status

Generic basic auth Authorization header field parser for whatever.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install basic-auth 

API

varauth=require('basic-auth')

auth(req)

Get the basic auth credentials from the given request. The Authorization header is parsed and if the header is invalid, undefined is returned, otherwise an object with name and pass properties.

auth.parse(string)

Parse a basic auth authorization header string. This will return an object with name and pass properties, or undefined if the string is invalid.

Example

Pass a Node.js request object to the module export. If parsing fails undefined is returned, otherwise an object with .name and .pass.

varauth=require('basic-auth')varuser=auth(req)// =>{name: 'something', pass: 'whatever' }

A header string from any other location can also be parsed with auth.parse, for example a Proxy-Authorization header:

varauth=require('basic-auth')varuser=auth.parse(req.getHeader('Proxy-Authorization'))

With vanilla node.js http server

varhttp=require('http')varauth=require('basic-auth')varcompare=require('tsscmp')// Create servervarserver=http.createServer(function(req,res){varcredentials=auth(req)// Check credentials// The "check" function will typically be against your user storeif(!credentials||!check(credentials.name,credentials.pass)){res.statusCode=401res.setHeader('WWW-Authenticate','Basic realm="example"')res.end('Access denied')}else{res.end('Access granted')}})// Basic function to validate credentials for examplefunctioncheck(name,pass){varvalid=true// Simple method to prevent short-circuit and use timing-safe comparevalid=compare(name,'john')&&validvalid=compare(pass,'secret')&&validreturnvalid}// Listenserver.listen(3000)

License

MIT

About

Generic basic auth Authorization header field parser

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Contributors 16