15
章節15
新增身份驗證
在前一章節中,您完成了發票路由的建置,加入了表單驗證並改善了易用性。在本章節中,您將為儀表板新增身份驗證。
在本章節中...
以下是我們將涵蓋的主題
什麼是身份驗證。
如何使用 NextAuth.js 將身份驗證新增至您的應用程式。
如何使用中介層重新導向使用者並保護您的路由。
如何使用 React 的 useActionState
來處理待處理狀態和表單錯誤。
什麼是身份驗證?
身份驗證是現今許多網路應用程式的關鍵部分。它是系統檢查使用者是否為其所聲稱身分的方式。
安全的網站通常使用多種方式來驗證使用者的身分。例如,在輸入您的使用者名稱和密碼後,網站可能會傳送驗證碼到您的裝置,或使用 Google Authenticator 等外部應用程式。這種雙重驗證 (2FA) 有助於提高安全性。即使有人得知您的密碼,他們也無法在沒有您獨特權杖的情況下存取您的帳戶。
身份驗證 vs. 授權
在網路開發中,身份驗證和授權扮演不同的角色
- 身份驗證是為了確保使用者是他們所聲稱的身分。您需要用您擁有的東西(例如使用者名稱和密碼)來證明您的身分。
- 授權是下一步。一旦使用者的身分得到確認,授權會決定他們被允許使用應用程式的哪些部分。
因此,身份驗證檢查你是誰,而授權決定你可以在應用程式中做什麼或存取什麼。
建立登入路由
首先在您的應用程式中建立一個名為 /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 />
,您將在本章稍後更新它。此元件以 React <Suspense>
包裹,因為它將存取來自傳入請求的資訊(URL 搜尋參數)。
NextAuth.js
我們將使用NextAuth.js為您的應用程式新增身份驗證。NextAuth.js 抽象化了管理工作階段、登入和登出以及身份驗證其他方面的許多複雜性。雖然您可以手動實作這些功能,但此過程可能既耗時又容易出錯。NextAuth.js 簡化了此過程,為 Next.js 應用程式中的身份驗證提供統一的解決方案。
設定 NextAuth.js
透過在終端機中執行以下命令來安裝 NextAuth.js
pnpm i next-auth@beta
在這裡,您正在安裝 NextAuth.js 的 beta
版本,它與 Next.js 14+ 相容。
接下來,為您的應用程式產生一個密鑰。此密鑰用於加密 Cookie,確保使用者工作階段的安全性。您可以透過在終端機中執行以下命令來執行此操作
# macOS
openssl rand -base64 32
# Windows can use https://generate-secret.vercel.app/32
然後,在您的 .env
檔案中,將您產生的密鑰新增至 AUTH_SECRET
變數
AUTH_SECRET=your-secret-key
為了使身份驗證在生產環境中運作,您也需要更新 Vercel 專案中的環境變數。請查看此指南,了解如何在 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 中介層保護您的路由
接下來,新增邏輯以保護您的路由。這將防止使用者存取儀表板頁面,除非他們已登入。
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
選項來指定它應該在特定路徑上執行。
為此任務採用中介層的優點是,受保護的路由甚至在 Middleware 驗證身份驗證之前都不會開始呈現,從而增強您的應用程式的安全性與效能。
密碼雜湊處理
在將密碼儲存在資料庫之前,雜湊處理密碼是一種良好的實務作法。雜湊處理將密碼轉換為固定長度的字元串,該字元串看起來是隨機的,即使使用者的資料洩露,也能提供一層安全性。
在植入資料庫時,您使用了名為 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,
});
新增憑證提供者
接下來,您需要為 NextAuth.js 新增 providers
選項。providers
是一個陣列,您可以在其中列出不同的登入選項,例如 Google 或 GitHub。在本課程中,我們將專注於僅使用憑證提供者。
憑證提供者允許使用者使用使用者名稱和密碼登入。
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 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
以檢查密碼是否相符
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
函數
'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
來呼叫伺服器動作、處理表單錯誤並顯示表單的待處理狀態
'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
函數
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
這有幫助嗎?