15
章節15
新增驗證功能
在上一章中,您透過新增表單驗證和改善無障礙功能完成了發票路由的建置。在本章中,您將為您的儀表板新增驗證功能。
本章內容…
以下是我們將涵蓋的主題
什麼是驗證。
如何使用 NextAuth.js 為您的應用程式新增驗證功能。
如何使用中介軟體重新導向使用者和保護您的路由。
如何使用 React 的 useActionState
來處理擱處理狀態和表單錯誤。
什麼是驗證?
驗證是現今許多網路應用程式的關鍵部分。它是系統檢查使用者是否為其聲稱身分的方式。
安全的網站通常會使用多種方式來檢查使用者的身分。例如,在輸入您的使用者名稱和密碼後,網站可能會將驗證碼傳送到您的裝置,或使用外部應用程式,例如 Google Authenticator。這種雙因素驗證 (2FA) 有助於提高安全性。即使有人得知您的密碼,他們也無法在沒有您的唯一權杖的情況下存取您的帳戶。
驗證與授權
在網頁開發中,驗證和授權扮演著不同的角色。
- 驗證是指確認使用者身份的真實性。您需要使用您擁有的東西(例如使用者名稱和密碼)來證明您的身份。
- 授權是後續步驟。一旦確認了使用者的身份,授權就會決定允許他們使用應用程式的哪些部分。
因此,驗證會檢查您的身份,而授權則決定您可以在應用程式中執行哪些操作或存取哪些內容。
建立登入路由
首先,在您的應用程式中建立一個名為 /login
的新路由,並貼上以下程式碼
import AcmeLogo from '@/app/ui/acme-logo';
import LoginForm from '@/app/ui/login-form';
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>
<LoginForm />
</div>
</main>
);
}
您會注意到頁面導入了 <LoginForm />
,您將在本章稍後更新它。
NextAuth.js 來為您的應用程式新增驗證功能。NextAuth.js 提取了管理工作階段、登入和登出以及驗證其他方面的許多複雜性。雖然您可以手動實作這些功能,但過程可能既耗時又容易出錯。NextAuth.js 簡化了流程,為 Next.js 應用程式中的驗證提供統一的解決方案。
設定 NextAuth.js
透過在終端機中執行以下指令來安裝 NextAuth.js
pnpm i next-auth@beta
這裡安裝的是 NextAuth.js 的 beta
版本,它與 Next.js 14 相容。
接下來,為您的應用程式產生一個密鑰。此密鑰用於加密 Cookie,確保使用者工作階段的安全性。您可以在終端機中執行以下指令來完成此操作
openssl rand -base64 32
接著,在您的 .env
檔案中,將產生的金鑰添加到 AUTH_SECRET
變數
AUTH_SECRET=your-secret-key
為了讓驗證功能在正式環境中運作,您也需要在 Vercel 專案中更新環境變數。參考這個指南
新增 pages 選項
在專案的根目錄建立一個 auth.config.ts
檔案,並匯出一個 authConfig
物件。這個物件將包含 NextAuth.js 的設定選項。目前,它只包含 pages
選項。
import type { NextAuthConfig } from 'next-auth';
export const authConfig = {
pages: {
signIn: '/login',
},
} satisfies NextAuthConfig;
您可以使用 pages
選項來指定自訂登入、登出和錯誤頁面的路由。這並非必要,但藉由在 pages
選項中新增 signIn: '/login'
,使用者將會被重新導向到我們的自訂登入頁面,而不是 NextAuth.js 的預設頁面。
使用 Next.js 中介軟體保護您的路由 /auth.config.tsimport 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;
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 中介軟體存取頁面。它會在請求完成之前被呼叫,並接收一個包含 auth
和 request
屬性的物件。auth
屬性包含使用者的工作階段,而 request
屬性包含傳入的請求。
providers
選項是一個陣列,您可以在其中列出不同的登入選項。目前,它是一個空陣列以滿足 NextAuth 設定。您將在新增憑證提供者章節中了解更多相關資訊。
接下來,您需要將 authConfig
物件匯入中介軟體檔案。在專案的根目錄中,建立一個名為 middleware.ts
的檔案,並貼上以下程式碼。
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export default NextAuth(authConfig).auth;
export const config = {
// https://nextjs.dev.org.tw/docs/app/building-your-application/routing/middleware#matcher
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};
這裡您使用 authConfig
物件初始化 NextAuth.js,並匯出 auth
屬性。您也使用了中介軟體的 matcher
選項來指定它應該在特定路徑上執行。
使用中介軟體執行此任務的優點是,在中介軟體驗證身份驗證之前,受保護的路由甚至不會開始渲染,從而提高了應用程式的安全性和效能。
密碼雜湊
在將密碼儲存到資料庫之前,將密碼進行**雜湊處理**是一個良好的實務作法。雜湊會將密碼轉換成固定長度的字元字串,看起來是隨機的,即使使用者資料外洩也能提供一層安全性。
在您的 seed.js
檔案中,您使用了一個名為 bcrypt
的套件,在將使用者密碼儲存到資料庫之前對其進行雜湊處理。在本章稍後,您將*再次*使用它來比較使用者輸入的密碼與資料庫中的密碼是否相符。但是,您需要為 bcrypt
套件建立一個單獨的檔案。這是因為 bcrypt
仰賴 Next.js 中介軟體中沒有的 Node.js API。
建立一個名為 auth.ts
的新檔案,並展開您的 authConfig
物件
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export const { auth, signIn, signOut } = NextAuth({
...authConfig,
});
新增憑證提供者 憑證提供者 。
憑證提供者允許使用者使用使用者名稱和密碼登入。
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
在檢查使用者是否存在於資料庫之前驗證電子郵件和密碼。
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
函式,從資料庫查詢使用者。
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import { z } from 'zod';
import { sql } from '@vercel/postgres';
import type { User } from '@/app/lib/definitions';
import bcrypt from 'bcrypt';
async function getUser(email: string): Promise<User | undefined> {
try {
const user = await sql<User>`SELECT * FROM users WHERE email=${email}`;
return user.rows[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
來檢查密碼是否相符。
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import { sql } from '@vercel/postgres';
import { z } from 'zod';
import type { User } from '@/app/lib/definitions';
import bcrypt from 'bcrypt';
// ...
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
函式。
'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'
錯誤,您需要顯示適當的錯誤訊息。您可以在文件中
最後,在您的 login-form.tsx
元件中,您可以使用 React 的 useActionState
來呼叫伺服器動作,處理表單錯誤,並顯示表單的待處理狀態。
'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';
export default function LoginForm() {
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>
<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
函式。
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();
}}
>
<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