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] (對象,默認為{} ):傳遞到用於服務文件的基礎服務靜態模塊的選項(請參見此處的用法示例)。