簡易的に認証をかけたいときに便利なBASIC認証。Expressでは標準の機能に用意されているようですが(使ったこと無いので詳しくは不明)ノーマルのNode.js+httpモジュールでBASIC認証を使う方法をメモ。
basic-auth
要はbasic-authというモジュールがあるのでそれを使いたいのですが、サンプル通りだと動かなかった。
こんな感じにすると動く。
basic_auth.js
const http = require('http')
const auth = require('basic-auth')
const name = 'username'
const password = 'pass'
const server = http.createServer(function (req,res) {
const credential = auth(req)
if (!credential || credential.name !== name || credential.pass !== password) {
res.writeHead(401,{'WWW-Authenticate':'Basic realm="secret zone"'})
res.end('Access denied')
} else {
res.end('Access granted')
}
}).listen(8080)
console.log('Server listening...')
サンプルだと200が返ってきてしまってうまく行かなかった。なんでやろ。