🔐

NextjsでBasic認証

に公開

Basic認証とは?

HTTPで定義される認証方式の一つ。
IDとパスワードをBase64でエンコードしてHTTPヘッダのAuthorizationフィールドに記載しサーバーに送信、サーバー側で照合する。

NextjsでのBasic認証実装

middlewareで実装
middlewareについては👇の記事を参照
https://zenn.dev/fi_freelance/articles/297f76e06e0270

実装内容

src/middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
export function middleware(req: NextRequest) {

    // リクエストのHeaderから'authorization'パラメーターを取得
    const basicAuth = req.headers.get('authorization')

    if (basicAuth) {
        // Base64文字列をバイナリ文字列へ変換 → 文字列を':'で分割して配列に!!
        const authValue = basicAuth.split(' ')[1]
        const [user, pwd] = Buffer.from(authValue, "base64").toString().split(':')

        // ユーザー名とパスワードの照合
        // ※実際の実装では"USER" "PWD"は.envに記載してください🙇‍♂️
        if (user === "USER" && pwd === "PWD") {
            return NextResponse.next()
        }
    }

    // BASIC認証に失敗した場合、エラーを表示する⛔
    return NextResponse.json(
        { error: "Basic Auth Required" },
        {
            headers: { "WWW-Authenticate": 'Basic realm="Secure Area"' },
            status: 401,
        }
    );
}
 
export const config = {
 // ここでBasic認証の対象となるパスを指定
  matcher: ['/about/:path*', '/dashboard/:path*']
}

Discussion