6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nuxt 3 の Server Middleware を使って Basic 認証を実装する

Last updated at Posted at 2022-06-30

概要

タイトル通り、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
./.env
BASIC_AUTH_ENABLED=true
BASIC_AUTH_USER=user
BASIC_AUTH_PASSWORD=password
./nuxt.config.ts
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,
  },
});
./server/middleware/basicAuth.ts
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");
});

動作確認

スクリーンショット 2022-07-01 2.26.19.png

http://localhost:3000 にアクセスして Basic 認証が作動していれば成功です。

あとがき

以上、Nuxt 3 の Server Middleware を使った Basic 認証の実装方法についてでした。

6
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?