项目作者: jshttp

项目描述 :
Generic basic auth Authorization header field parser
高级语言: JavaScript
项目地址: git://github.com/jshttp/basic-auth.git
创建时间: 2013-11-29T20:10:24Z
项目社区:https://github.com/jshttp/basic-auth

开源协议:MIT License

下载


basic-auth

NPM Version
NPM Downloads
Node.js Version
Build Status
Coverage 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:

  1. $ npm install basic-auth

API

  1. var auth = 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.

  1. var auth = require('basic-auth')
  2. var user = auth(req)
  3. // => { name: 'something', pass: 'whatever' }

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

  1. var auth = require('basic-auth')
  2. var user = auth.parse(req.getHeader('Proxy-Authorization'))

With vanilla node.js http server

  1. var http = require('http')
  2. var auth = require('basic-auth')
  3. var compare = require('tsscmp')
  4. // Create server
  5. var server = http.createServer(function (req, res) {
  6. var credentials = auth(req)
  7. // Check credentials
  8. // The "check" function will typically be against your user store
  9. if (!credentials || !check(credentials.name, credentials.pass)) {
  10. res.statusCode = 401
  11. res.setHeader('WWW-Authenticate', 'Basic realm="example"')
  12. res.end('Access denied')
  13. } else {
  14. res.end('Access granted')
  15. }
  16. })
  17. // Basic function to validate credentials for example
  18. function check (name, pass) {
  19. var valid = true
  20. // Simple method to prevent short-circuit and use timing-safe compare
  21. valid = compare(name, 'john') && valid
  22. valid = compare(pass, 'secret') && valid
  23. return valid
  24. }
  25. // Listen
  26. server.listen(3000)

License

MIT