LoginSignup
4
4

More than 3 years have passed since last update.

Node.jsでBASIC認証.

Last updated at Posted at 2019-12-05

Node.jsでBASIC認証

Node.jsでexpressを使ったWebサーバでBASIC認証を導入する場合の実装方法について紹介します.
本記事上では,パスワードを暗号化・ハッシュ化せずにソースコード上に記載しております.セキュリティ上望ましくない点にご注意ください.

BASIC認証の導入

expressでBASIC認証を導入するにはexpress-basic-authを使用します.下記がそのサンプルコードです.

const express = require("express")
const basicAuth = require("express-basic-auth")

// 正解のユーザ名とパスワード
const correctUserName = "hiroyky"
const correctPassword = "password"

const app = express();
app.use(basicAuth({
    challenge: true,
    unauthorizedResponse: () => {
        return "Unauthorized" // 認証失敗時に表示するメッセージ
    },
    authorizer(username, password) => {
        const userMatch = basicAuth.safeCompare(username, correctUserName)
        const passMatch = basicAuth.safeCompare(password, correctPassword)

        return userMatch & passMatch
    }
}))

basicAuthをexpressのミドルウェアとして登録しています.引数のオブジェクト中のauthorizerに認証用関数を書きます.戻り値がtrueの場合,認証OK,falseなら否認です.

このとき注意したいのが公式ドキュメントにもあるように下記の記載です.内容としては以下の実装を推奨しています.素直に従っておきましょう.

  • 比較に=====といった演算子を用いない,safeComapre関数によって比較する
  • return userMatch & passMatchのように論理演算によって値を出力する

When using your own authorizer, make sure not to use standard string comparison (== / ===) when comparing user input with secret credentials, as that would make you vulnerable against timing attacks. Use the provided safeCompare function instead - always provide the user input as its first argument. Also make sure to use bitwise logic operators (| and &) instead of the standard ones (|| and &&) for the same reason, as the standard ones use shortcuts.

これで,ひとまずBASIC認証を導入することができました.

4
4
3

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
4
4