Chapter 15: 認証
アクセシビリティまで整ったら,最後にダッシュボードを保護する仕組みを追加します。この章では Auth.js と Middleware を組み合わせ,ログインとルート保護を実装します。
この章で扱う内容
- 認証とは何か。
- Auth.js を使ってアプリに認証を追加する方法。
- Middleware を使ってリダイレクトとルート保護を行う方法。
useActionStateでペンディング状態とフォームエラーを扱う方法。
認証とは?
認証は,多くの Web アプリで不可欠な機能で,ユーザーが本人であることを確認する仕組みです。 ユーザー名とパスワードに加えて,SMS や認証アプリによる 2 要素認証 (2FA) を用いることで,漏えい時のリスクを下げられます。
Authentication と Authorization の違い
- Authentication(認証):あなたが誰かを確かめる(例:メールアドレスとパスワード)。
- Authorization(認可):あなたが何にアクセスできるかを決める(例:管理画面へのアクセス権)。
ログインルートの作成
/login ルートを作り,次のコードを貼り付けます。
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 /> は後で更新します。URL 検索パラメータを読むため,<Suspense> で囲っています。
Auth.js
この章では Auth.js を使います。セッション管理,サインイン/サインアウトなどの複雑さを抽象化し,Next.js アプリでの認証をシンプルにします。
セットアップ
ターミナルで Auth.js をインストールします(Next.js 14+ 対応の beta)。
次に,暗号化キーを生成し,Cookie の暗号化に使います。
.env に追加します。
本番運用では,Vercel のプロジェクト設定にも同じ環境変数を追加してください。
pages オプションを追加
プロジェクト直下に auth.config.ts を作成し,NextAuth の設定オブジェクトをエクスポートします。ここでは,カスタムサインインページのパスを指定します。
import type { NextAuthConfig } from 'next-auth';
export const authConfig = {
pages: {
signIn: '/login',
},
} satisfies NextAuthConfig;
pages.signIn を設定すると,NextAuth のデフォルトページではなく,自作の /login にリダイレクトされます。
Middleware でルートを保護する
ダッシュボード配下はログイン済みでなければアクセスできないようにします。authorized コールバックで判定します。
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; // 未認証はログインページへ
} else if (isLoggedIn) {
return Response.redirect(new URL('/dashboard', nextUrl));
}
return true;
},
},
providers: [], // 後で追加。いったん空配列
} satisfies NextAuthConfig;
次に,middleware.ts でこの設定を使います。
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export default NextAuth(authConfig).auth;
export const config = {
// 実行対象のパスを指定
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
runtime: 'nodejs',
};
Middleware を使う利点は,保護ルートがレンダリングを始める前に認証を検証できる点です。
パスワードハッシュ
パスワードはハッシュ化して保存するのが基本です。シード時に bcrypt でハッシュ化しました。以降の照合でも使いますが,bcrypt は Middleware で使えない Node API に依存するため,Middleware 外から呼べるように分離します。
auth.ts を作成し,authConfig を展開してエクスポートします。
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export const { auth, signIn, signOut } = NextAuth({
...authConfig,
});
Credentials プロバイダの追加
このコースでは メール+パスワード の Credentials を使います。
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 や email など他のプロバイダも利用できます。詳細は Auth.js ドキュメントへ。
サインイン処理の実装
authorize で認証ロジックを書きます。まず Zod で入力を検証します。
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);
},
}),
],
});
次に,DB からユーザーを取得する getUser を定義します。
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 で照合します。一致したら user を返し,そうでなければ null を返します。
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) {
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;
const passwordsMatch = await bcrypt.compare(password, user.password);
if (passwordsMatch) return user;
}
console.log('Invalid credentials');
return null;
},
}),
],
});
ログインフォームの更新
actions.ts に authenticate アクションを追加し,auth.ts の signIn を呼び出します。
'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;
}
}
login-form.tsx では useActionState を使って,サーバーアクションの呼び出し,エラー表示,送信中状態を扱います。URL の callbackUrl があれば隠しフィールドで渡します。
'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 /> で auth.ts の signOut を呼び出します。
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>
);
}
試してみよう
次の資格情報で,アプリにログイン/ログアウトできるはずです。
- Email:
user@nextmail.com - Password:
123456