basic-auth 是一个通用基本身份验证授权头字段解析器。
这是一个 Node.js 模块,可通过 npm registry 获得。安装是使用以下npm install 命令完成的 :
$ npm install basic-auth
var auth = require('basic-auth')
从给定请求中获取基本身份验证凭据。的Authorization 报头进行解析,并且如果首部是无效的,undefined则返回,否则将物体与name和pass属性。
解析基本身份验证授权标头字符串。这将返回一个具有name和pass属性的对象,或者undefined如果字符串无效。
将 Node.js 请求对象传递给模块导出。如果解析失败 undefined则返回,否则返回一个带有.nameand的对象.pass。
var auth = require('basic-auth')
var user = auth(req)
// => { name: 'something', pass: 'whatever' }
来自任何其他位置的标头字符串也可以用 解析 auth.parse,例如Proxy-Authorization标头:
var auth = require('basic-auth')
var user = auth.parse(req.getHeader('Proxy-Authorization'))
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)

