使用原生 JavaScript 的简单基本身份验证(ES6)
app.use((req, res, next) => {
// -----------------------------------------------------------------------
// authentication middleware
const auth = {login: 'yourlogin', password: 'yourpassword'} // change this
// parse login and password from headers
const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
const [login, password] = Buffer.from(b64auth, 'base64').toString().split(':')
// Verify login and password are set and correct
if (login && password && login === auth.login && password === auth.password) {
// Access granted...
return next()
}
// Access denied...
res.set('WWW-Authenticate', 'Basic realm="401"') // change this
res.status(401).send('Authentication required.') // custom message
// -----------------------------------------------------------------------
})
注意:这个“中间件”可以在任何处理程序中使用。只需删除 next() 并反转逻辑即可。请参阅下面的 1-statement 示例,或此答案的 edit history。
为什么?
-
req.headers.authorization 包含值“Basic <base64 string>”,但它也可以为空,我们不希望它失败,因此 || '' 的奇怪组合
- 节点不知道
atob() 和btoa(),因此Buffer
ES6 -> ES5
const 只是 var .. 有点
(x, y) => {...} 只是 function(x, y) {...}
const [login, password] = ...split() 只是两个 var 作业合二为一
source of inspiration (uses packages)
以上是一个
超级简单示例,旨在
超级短并快速部署到您的游乐场服务器。但正如 cmets 中所指出的,密码也可以包含冒号字符
:。要从
b64auth 中正确提取它,您可以使用它。
// parse login and password from headers
const b64auth = (req.headers.authorization || '').split(' ')[1] || ''
const strauth = Buffer.from(b64auth, 'base64').toString()
const splitIndex = strauth.indexOf(':')
const login = strauth.substring(0, splitIndex)
const password = strauth.substring(splitIndex + 1)
// using shorter regex by @adabru
// const [_, login, password] = strauth.match(/(.*?):(.*)/) || []
一个语句中的基本身份验证
...另一方面,如果您只使用一个或很少的登录名,这是您需要的最低要求:(您甚至根本不需要解析凭据)
function (req, res) {
//btoa('yourlogin:yourpassword') -> "eW91cmxvZ2luOnlvdXJwYXNzd29yZA=="
//btoa('otherlogin:otherpassword') -> "b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk"
// Verify credentials
if ( req.headers.authorization !== 'Basic eW91cmxvZ2luOnlvdXJwYXNzd29yZA=='
&& req.headers.authorization !== 'Basic b3RoZXJsb2dpbjpvdGhlcnBhc3N3b3Jk')
return res.status(401).send('Authentication required.') // Access denied.
// Access granted...
res.send('hello world')
// or call next() if you use it as middleware (as snippet #1)
}
PS:您是否需要同时拥有“安全”和“公共”路径?考虑改用express.router。
var securedRoutes = require('express').Router()
securedRoutes.use(/* auth-middleware from above */)
securedRoutes.get('path1', /* ... */)
app.use('/secure', securedRoutes)
app.get('public', /* ... */)
// example.com/public // no-auth
// example.com/secure/path1 // requires auth