コンテンツにスキップ

15

認証の追加

前の章では、請求書のルーティングにフォームバリデーションを追加し、アクセシビリティを改善して完成させました。この章では、ダッシュボードに認証を追加します。

このチャプターでは...

取り上げるトピックは以下の通りです。

認証とは?

NextAuth.js を使用してアプリに認証を追加する方法。

ミドルウェアを使用してユーザーをリダイレクトし、ルーティングを保護する方法。

React の useActionState を使用して、保留中の状態やフォームのエラーを処理する方法。

認証とは?

認証は、今日の多くのWebアプリケーションにおいて重要な部分です。システムがユーザーが本人であることをどのように確認するかということです。

安全なウェブサイトは、ユーザーの身元を確認するために複数の方法を使用することがよくあります。例えば、ユーザー名とパスワードを入力した後、サイトはデバイスに確認コードを送信したり、Google Authenticator のような外部アプリを使用したりします。この 2 要素認証(2FA)は、セキュリティの向上に役立ちます。たとえ誰かがあなたのパスワードを知ったとしても、ユニークなトークンなしではアカウントにアクセスできません。

認証 vs 認可

Web開発において、認証と認可は異なる役割を果たします。

  • 認証とは、ユーザーが本人であることを確認することです。ユーザー名とパスワードのような、あなたが持っているもので身元を証明しています。
  • 認可は次のステップです。ユーザーの身元が確認されたら、認可はアプリケーションのどの部分を使用することを許可されているかを決定します。

したがって、認証はあなたが誰であるかを確認し、認可はアプリケーションで何ができるか、または何にアクセスできるかを決定します。

ログインルートの作成

まず、アプリケーションに /login という新しいルートを作成し、次のコードを貼り付けます。

/app/login/page.tsx
import AcmeLogo from '@/app/ui/acme-logo';
import LoginForm from '@/app/ui/login-form';
import { Suspense } from 'react';
 
export default function LoginPage() {
  return (
    <main className="flex items-center justify-center md:h-screen">
      <div className="relative mx-auto flex w-full max-w-[400px] flex-col space-y-2.5 p-4 md:-mt-32">
        <div className="flex h-20 w-full items-end rounded-lg bg-blue-500 p-3 md:h-36">
          <div className="w-32 text-white md:w-36">
            <AcmeLogo />
          </div>
        </div>
        <Suspense>
          <LoginForm />
        </Suspense>
      </div>
    </main>
  );
}

ページは <LoginForm /> をインポートすることに気づくでしょう。これは、章の後半で更新します。このコンポーネントは、React の <Suspense> でラップされています。なぜなら、受信リクエスト(URL検索パラメータ)からの情報にアクセスするためです。

NextAuth.js

アプリケーションに認証を追加するために、NextAuth.js を使用します。NextAuth.js は、セッション管理、サインインとサインアウト、その他の認証関連の側面に関連する多くの複雑さを抽象化します。これらの機能を手動で実装することもできますが、プロセスは時間がかかり、エラーが発生しやすくなります。NextAuth.js はプロセスを簡素化し、Next.js アプリケーションの認証のための統一されたソリューションを提供します。

NextAuth.js のセットアップ

ターミナルで次のコマンドを実行して、NextAuth.js をインストールします。

ターミナル
pnpm i next-auth@beta

ここでは、Next.js 14+ と互換性のある NextAuth.js の beta バージョンをインストールしています。

次に、アプリケーションのシークレットキーを生成します。このキーはクッキーを暗号化するために使用され、ユーザーセッションのセキュリティを確保します。ターミナルで次のコマンドを実行することで、これを行うことができます。

ターミナル
# macOS
openssl rand -base64 32
# Windows can use https://generate-secret.vercel.app/32

次に、.env ファイルで、生成したキーを AUTH_SECRET 変数に追加します。

.env
AUTH_SECRET=your-secret-key

本番環境で認証を機能させるには、Vercel プロジェクトの環境変数も更新する必要があります。Vercel で環境変数を追加する方法については、このガイドをご覧ください。

ページオプションの追加

プロジェクトのルートに auth.config.ts という名前の新しいファイルを作成し、authConfig オブジェクトをエクスポートします。このオブジェクトには、NextAuth.js の設定オプションが含まれます。現時点では、pages オプションのみが含まれます。

/auth.config.ts
import type { NextAuthConfig } from 'next-auth';
 
export const authConfig = {
  pages: {
    signIn: '/login',
  },
} satisfies NextAuthConfig;

pages オプションを使用して、カスタムサインイン、サインアウト、エラーページのルートを指定できます。これは必須ではありませんが、pages オプションに signIn: '/login' を追加することで、NextAuth.js のデフォルトページではなく、カスタムログインページにユーザーがリダイレクトされます。

Next.js ミドルウェアでルーティングを保護する

次に、ルーティングを保護するためのロジックを追加します。これにより、ユーザーがログインしていない限り、ダッシュボードページにアクセスできなくなります。

/auth.config.ts
import type { NextAuthConfig } from 'next-auth';
 
export const authConfig = {
  pages: {
    signIn: '/login',
  },
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user;
      const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
      if (isOnDashboard) {
        if (isLoggedIn) return true;
        return false; // Redirect unauthenticated users to login page
      } else if (isLoggedIn) {
        return Response.redirect(new URL('/dashboard', nextUrl));
      }
      return true;
    },
  },
  providers: [], // Add providers with an empty array for now
} satisfies NextAuthConfig;

authorized コールバックは、Next.js ミドルウェアでページにアクセスするためにリクエストが承認されているかどうかを確認するために使用されます。リクエストが完了する前に呼び出され、authrequest プロパティを持つオブジェクトを受け取ります。auth プロパティにはユーザーのセッションが含まれ、request プロパティには受信リクエストが含まれます。

providers オプションは、さまざまなログインオプションをリストする配列です。現時点では、NextAuth の設定を満たすために空の配列です。これについては、「認証情報プロバイダーの追加」セクションで詳しく説明します。

次に、authConfig オブジェクトをミドルウェアファイルにインポートする必要があります。プロジェクトのルートに middleware.ts という名前のファイルを作成し、次のコードを貼り付けます。

/middleware.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
 
export default NextAuth(authConfig).auth;
 
export const config = {
  // https://nextjs.dokyumento.jp/docs/app/building-your-application/routing/middleware#matcher
  matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
  runtime: 'nodejs',
};

ここでは、authConfig オブジェクトで NextAuth.js を初期化し、auth プロパティをエクスポートしています。また、ミドルウェアの matcher オプションを使用して、特定のパスで実行されるように指定しています。

このタスクにミドルウェアを採用する利点は、ミドルウェアが認証を確認するまで保護されたルーティングがレンダリングを開始しないことであり、アプリケーションのセキュリティとパフォーマンスの両方を向上させます。

パスワードハッシュ

パスワードをデータベースに保存する前にハッシュすることは良い習慣です。ハッシュは、パスワードを固定長の文字列に変換し、ランダムに見えるようにして、ユーザーのデータが漏洩した場合でもセキュリティ層を提供します。

データベースのシード処理時に、bcrypt というパッケージを使用して、ユーザーのパスワードをデータベースに保存する前にハッシュしました。この章の後半で、データベース内のパスワードとユーザーが入力したパスワードを比較するために、再度使用します。ただし、bcrypt パッケージ用の別のファイルを作成する必要があります。これは、bcrypt が Next.js ミドルウェアでは利用できない Node.js API に依存しているためです。

authConfig オブジェクトを展開する新しいファイル auth.ts を作成します。

/auth.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
});

認証情報プロバイダーの追加

次に、NextAuth.js の providers オプションを追加する必要があります。providers は、Google や GitHub のようなさまざまなログインオプションをリストする配列です。このコースでは、認証情報プロバイダーのみを使用することに焦点を当てます。

認証情報プロバイダーを使用すると、ユーザーはユーザー名とパスワードでログインできます。

/auth.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import Credentials from 'next-auth/providers/credentials';
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [Credentials({})],
});

知っておくと良いこと

他にも、OAuthメール のような他の代替プロバイダーがあります。オプションの完全なリストについては、NextAuth.js ドキュメント を参照してください。

サインイン機能の追加

authorize 関数を使用して認証ロジックを処理できます。サーバーアクションと同様に、zod を使用して、ユーザーがデータベースに存在するかどうかを確認する前に、メールとパスワードを検証できます。

/auth.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import Credentials from 'next-auth/providers/credentials';
import { z } from 'zod';
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [
    Credentials({
      async authorize(credentials) {
        const parsedCredentials = z
          .object({ email: z.string().email(), password: z.string().min(6) })
          .safeParse(credentials);
      },
    }),
  ],
});

資格情報を検証した後、データベースからユーザーをクエリする新しい getUser 関数を作成します。

/auth.ts
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import { z } from 'zod';
import type { User } from '@/app/lib/definitions';
import bcrypt from 'bcrypt';
import postgres from 'postgres';
 
const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' });
 
async function getUser(email: string): Promise<User | undefined> {
  try {
    const user = await sql<User[]>`SELECT * FROM users WHERE email=${email}`;
    return user[0];
  } catch (error) {
    console.error('Failed to fetch user:', error);
    throw new Error('Failed to fetch user.');
  }
}
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [
    Credentials({
      async authorize(credentials) {
        const parsedCredentials = z
          .object({ email: z.string().email(), password: z.string().min(6) })
          .safeParse(credentials);
 
        if (parsedCredentials.success) {
          const { email, password } = parsedCredentials.data;
          const user = await getUser(email);
          if (!user) return null;
        }
 
        return null;
      },
    }),
  ],
});

次に、bcrypt.compare を呼び出して、パスワードが一致するかどうかを確認します。

/auth.ts
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import { z } from 'zod';
import type { User } from '@/app/lib/definitions';
import bcrypt from 'bcrypt';
import postgres from 'postgres';
 
const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' });
 
// ...
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [
    Credentials({
      async authorize(credentials) {
        // ...
 
        if (parsedCredentials.success) {
          const { email, password } = parsedCredentials.data;
          const user = await getUser(email);
          if (!user) return null;
          const passwordsMatch = await bcrypt.compare(password, user.password);
 
          if (passwordsMatch) return user;
        }
 
        console.log('Invalid credentials');
        return null;
      },
    }),
  ],
});

最後に、パスワードが一致する場合はユーザーを返します。一致しない場合は、null を返して、ユーザーがログインできないようにします。

ログインフォームの更新

次に、認証ロジックをログインフォームに接続する必要があります。actions.ts ファイルで、authenticate という名前の新しいアクションを作成します。このアクションは、auth.ts から signIn 関数をインポートする必要があります。

/app/lib/actions.ts
'use server';
 
import { signIn } from '@/auth';
import { AuthError } from 'next-auth';
 
// ...
 
export async function authenticate(
  prevState: string | undefined,
  formData: FormData,
) {
  try {
    await signIn('credentials', formData);
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case 'CredentialsSignin':
          return 'Invalid credentials.';
        default:
          return 'Something went wrong.';
      }
    }
    throw error;
  }
}

'CredentialsSignin' エラーが発生した場合は、適切なエラーメッセージを表示したいと考えます。NextAuth.js のエラーについては、ドキュメント で学習できます。

最後に、login-form.tsx コンポーネントで、React の useActionState を使用してサーバーアクションを呼び出し、フォームエラーを処理し、フォームの保留中状態を表示できます。

app/ui/login-form.tsx
'use client';
 
import { lusitana } from '@/app/ui/fonts';
import {
  AtSymbolIcon,
  KeyIcon,
  ExclamationCircleIcon,
} from '@heroicons/react/24/outline';
import { ArrowRightIcon } from '@heroicons/react/20/solid';
import { Button } from '@/app/ui/button';
import { useActionState } from 'react';
import { authenticate } from '@/app/lib/actions';
import { useSearchParams } from 'next/navigation';
 
export default function LoginForm() {
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/dashboard';
  const [errorMessage, formAction, isPending] = useActionState(
    authenticate,
    undefined,
  );
 
  return (
    <form action={formAction} className="space-y-3">
      <div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8">
        <h1 className={`${lusitana.className} mb-3 text-2xl`}>
          Please log in to continue.
        </h1>
        <div className="w-full">
          <div>
            <label
              className="mb-3 mt-5 block text-xs font-medium text-gray-900"
              htmlFor="email"
            >
              Email
            </label>
            <div className="relative">
              <input
                className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
                id="email"
                type="email"
                name="email"
                placeholder="Enter your email address"
                required
              />
              <AtSymbolIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
            </div>
          </div>
          <div className="mt-4">
            <label
              className="mb-3 mt-5 block text-xs font-medium text-gray-900"
              htmlFor="password"
            >
              Password
            </label>
            <div className="relative">
              <input
                className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
                id="password"
                type="password"
                name="password"
                placeholder="Enter password"
                required
                minLength={6}
              />
              <KeyIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
            </div>
          </div>
        </div>
        <input type="hidden" name="redirectTo" value={callbackUrl} />
        <Button className="mt-4 w-full" aria-disabled={isPending}>
          Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
        </Button>
        <div
          className="flex h-8 items-end space-x-1"
          aria-live="polite"
          aria-atomic="true"
        >
          {errorMessage && (
            <>
              <ExclamationCircleIcon className="h-5 w-5 text-red-500" />
              <p className="text-sm text-red-500">{errorMessage}</p>
            </>
          )}
        </div>
      </div>
    </form>
  );
}

ログアウト機能の追加

<SideNav /> にログアウト機能を追加するには、<form> 要素で auth.ts から signOut 関数を呼び出します。

/ui/dashboard/sidenav.tsx
import Link from 'next/link';
import NavLinks from '@/app/ui/dashboard/nav-links';
import AcmeLogo from '@/app/ui/acme-logo';
import { PowerIcon } from '@heroicons/react/24/outline';
import { signOut } from '@/auth';
 
export default function SideNav() {
  return (
    <div className="flex h-full flex-col px-3 py-4 md:px-2">
      // ...
      <div className="flex grow flex-row justify-between space-x-2 md:flex-col md:space-x-0 md:space-y-2">
        <NavLinks />
        <div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div>
        <form
          action={async () => {
            'use server';
            await signOut({ redirectTo: '/' });
          }}
        >
          <button className="flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3">
            <PowerIcon className="w-6" />
            <div className="hidden md:block">Sign Out</div>
          </button>
        </form>
      </div>
    </div>
  );
}

試してみる

さて、試してみてください。次の認証情報を使用して、アプリケーションにログインおよびログアウトできるはずです。

  • メール: user@nextmail.com
  • パスワード: 123456

チャプターを完了しました。15

アプリケーションに認証を追加し、ダッシュボードのルーティングを保護しました。

次へ

16: メタデータの追加

共有の準備としてメタデータの追加方法を学習して、アプリケーションを完成させます。

App Router: 認証の追加 | Next.js