1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cloud Run + Next.js 上で Basic 認証

Posted at

こちらも情報が少なかったので書いてみました。
※ セキュリティのリスクがあるため、本番でのBasic認証は避けましょう...!

実装

src/middleware.tsを作成します

middleware.ts
export { default } from "next-auth/middleware";
import basicAuth from 'basic-auth';
import type { NextRequest } from 'next/server';

// ここに認証したいページを定義します
export const config = {
  matcher: [
    '/((?!api|static|.*\\..*|_next).*)',
  ],
};

export function middleware(req: NextRequest) {
  const credentials = basicAuth({ headers: { authorization: req.headers.get('authorization') || '' } });
  const username = process.env.BASIC_AUTH_USERNAME;
  const password = process.env.BASIC_AUTH_PASSWORD;

  if (
    !credentials ||
    !username ||
    !password ||
    credentials.name !== username ||
    credentials.pass !== password
  ) {
    return new Response('認証が必要です', {
      status: 401,
      headers: {
        'WWW-Authenticate': 'Basic realm="Protected Area"',
      },
    });
  }
}

あとは.envに下記の環境変数を設定するだけ!

BASIC_AUTH_USERNAME=<ユーザー名>
BASIC_AUTH_PASSWORD=<パスワード>

最後に

Basic認証は、簡単で便利ですがセキュリティとしてはリスクがあるため
長期運用する場合にはDigest認証、GCP の I AM 認証などを使うのをおすすめします。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?