Help us understand the problem. What is going on with this article?

Node.jsでBASIC認証.

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"
cosnt 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認証を導入することができました.

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした