概要
タイトル通り、Nuxt 3 の Server Middleware を使って Basic 認証を実装してみたいと思います。
- Server Middlewareとは
- サーバーリクエストの際に実行される関数
- 「server/middleware」以下にファイルを置く事で自動的に読み込まれる
Nuxt will automatically read in any file in the ~/server/middleware to create server middleware for your project.
Middleware handlers will run on every request before any other server route to add check and some headers, log requests, or extend the event's request object.
出典: https://v3.nuxtjs.org/guide/features/server-routes/#server-middleware
Nuxt.js で作ったアプリに Basic 認証を導入する方法としては nuxt-basic-auth-module などのライブラリを使用するパターンも考えられますが、今回はライブラリ未使用で進めます。
実装
$ touch .env
$ mkdir -p server/middleware
$ touch server/middleware/basicAuth.ts
BASIC_AUTH_ENABLED=true
BASIC_AUTH_USER=user
BASIC_AUTH_PASSWORD=password
import { defineNuxtConfig } from "nuxt";
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
privateRuntimeConfig: {
basic_auth_enabled: process.env.BASIC_AUTH_ENABLED,
basic_auth_user: process.env.BASIC_AUTH_USER,
basic_auth_password: process.env.BASIC_AUTH_PASSWORD,
},
});
export default defineEventHandler((event) => {
const config = useRuntimeConfig();
/* Basic 認証が不要な場合(開発環境など)は 「.env」 内の BASIC_AUTH_ENABLED を「false」に変更すれば OK */
if (config?.basic_auth_enabled !== "true") return;
const base64Credentials = event.req.headers?.authorization?.split(" ")?.[1];
if (base64Credentials) {
const credentials = Buffer.from(base64Credentials, "base64").toString("ascii");
const [username, password] = credentials.split(":");
if (
username === config?.basic_auth_user &&
password === config?.basic_auth_password
) return;
}
event.res.statusCode = 401;
event.res.setHeader("WWW-Authenticate", 'Basic realm="Secure Area"');
event.res.end("Unauthorized");
});
動作確認
http://localhost:3000 にアクセスして Basic 認証が作動していれば成功です。
あとがき
以上、Nuxt 3 の Server Middleware を使った Basic 認証の実装方法についてでした。