您当前的位置:首页 > 计算机 > 服务器 > 网络服务

basic-auth 通用身份验证授权 http 请求头字段解析器

时间:12-14来源:作者:点击数:

basic-auth 是一个通用基本身份验证授权头字段解析器。

安装

这是一个 Node.js 模块,可通过 npm registry 获得。安装是使用以下npm install 命令完成的 :

$ npm install basic-auth

应用程序接口

var auth = require('basic-auth')

auth(req)

从给定请求中获取基本身份验证凭据。的Authorization 报头进行解析,并且如果首部是无效的,undefined则返回,否则将物体与namepass属性。

auth.parse(string)

解析基本身份验证授权标头字符串。这将返回一个具有namepass属性的对象,或者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'))

使用 vanilla node.js http 服务器

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)

项目地址:https://github.com/jshttp/basic-auth

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐