LoginSignup
6
7

More than 5 years have passed since last update.

Node.jsでBASIC認証

Last updated at Posted at 2016-10-25

簡易的に認証をかけたいときに便利な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が返ってきてしまってうまく行かなかった。なんでやろ。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7