static auth
2.1.2
将基本身份验证添加到Vercel上的静态网站上的最简单方法。
我最初创建了这一点是为了在Vercel上托管的项目中添加一个身份验证层,但也可以与Node的内置http模块一起使用,并且应该与Express一起使用。
$ npm i static-auth -s
# or
$ yarn add static-auth const auth = require ( 'static-auth' ) ;
// Example with Vercel
module . exports = auth (
'/admin' ,
( user , pass ) => ( user === 'admin' && pass === 'admin' ) // (1)
) ;(1)通过
==或===操作员检查凭据使您的代码容易受到计时攻击。这可以通过使用“保险箱”软件包来解决。
index.js
const auth = require ( 'static-auth' ) ;
// create a handler that will check for basic authentication before serving the files
const serveHandler = auth ( /* ... */ ) ;
// start the server
const http = require ( 'http' ) ;
const server = http . createServer ( serveHandler ) ;
server . listen ( 4444 , ( ) => console . log ( 'Listening on port 4444...' ) ) ; auth(url, validator, [options])
必需的 :
url (字符串):通过基本身份验证保护的基本URL。使用/限制访问整个网站或/<path> (例如/admin )以仅限于您网站的一部分的访问。validator (函数):接受两个参数( user和pass )的函数,如果提供的登录凭据授予访问限制区域,则返回true 。选修的 :
[options] (对象):[directory] (字符串,默认为process.cwd() ):提供静态资产的基本路径。例如,如果向my-website.com/app.css的请求返回位于./www/app.css (相对于节点脚本)的文件的内容,则应将其设置为__dirname + '/www' ,否则脚本将寻找不存在的./app.css并返回404。[onAuthFailed] (函数):接受一个参数( res , http.ServerResponse对象)的回调,如果您想在提供的凭据无效时返回自定义错误消息或HTML页面,则有用。[realm] (字符串,默认为'default-realm' ):请参阅基本身份验证(stackoverflow)中的“领域”。[serveStaticOptions] (对象,默认为{} ):传递到用于服务文件的基础服务静态模块的选项(请参见此处的用法示例)。