static auth
2.1.2
Vercelでホストされている静的Webサイトに基本認証を追加する最も簡単な方法。
私はもともと、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)
==OR===オペレーターを介して資格情報をチェックすると、タイミング攻撃に対してコードが脆弱になります。これは、代わりにセーフコンパールパッケージを使用することで解決できます。
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。 /使用するには、Webサイト全体へのアクセスを制限するか、 /<path> >(Eg /admin )を使用して、サイトのセクションのみへのアクセスを制限します。validator ( function ):2つのパラメーター( userとpass )を受け入れ、提供されたログイン資格情報が制限領域へのアクセスを付与する場合にtrueを返す関数。オプション:
[options] (オブジェクト):[directory] ( String 、Defaults to process.cwd() ):静的資産を提供するベースパス。たとえば、 my-website.com/app.cssへのリクエストが./www/app.cssにあるファイルのコンテンツ(ノードスクリプトと比較)を返す場合、これを__dirname + '/www'に設定する必要があります。 __dirname + '/www' 、それ以外の場合は、スクリプトは./app.cssを探します - 存在しない - 404を返します。[onAuthFailed] ( function ):1つのパラメーター( res 、 http.ServerResponseオブジェクト)を受け入れるコールバック。[realm] ( String 、デフォルトは'default-realm'になります):Basic Authentication(StackOverFlow)の「Realm」とは何かを参照してください。[serveStaticOptions] (オブジェクト、デフォルトは{} ):ファイルの提供に使用される基礎となるサーブスタティックモジュールに渡すオプション(ここの使用例を参照)。