跳到內容
Pages Router指南身份驗證

如何在 Next.js 中實現身份驗證

瞭解身份驗證對於保護應用程式的資料至關重要。本頁面將指導您使用哪些 React 和 Next.js 功能來實現身份驗證。

在開始之前,將過程分解為三個概念會很有幫助:

  1. 身份驗證:驗證使用者是否是其自稱的身份。它要求使用者透過其擁有的東西(例如使用者名稱和密碼)來證明其身份。
  2. 會話管理:跨請求跟蹤使用者的身份驗證狀態。
  3. 授權:決定使用者可以訪問哪些路由和資料。

此圖顯示了使用 React 和 Next.js 功能的身份驗證流程

Diagram showing the authentication flow with React and Next.js features

本頁面上的示例出於教育目的,介紹了基本的使用者名稱和密碼身份驗證。雖然您可以實現自定義身份驗證解決方案,但為了提高安全性和簡化性,我們建議使用身份驗證庫。這些庫提供身份驗證、會話管理和授權的內建解決方案,以及社交登入、多因素身份驗證和基於角色的訪問控制等附加功能。您可以在身份驗證庫部分找到列表。

身份驗證

以下是實現註冊和/或登入表單的步驟:

  1. 使用者透過表單提交其憑據。
  2. 表單傳送由 API 路由處理的請求。
  3. 驗證成功後,流程完成,表示使用者已成功透過身份驗證。
  4. 如果驗證不成功,則會顯示錯誤訊息。

考慮一個使用者可以輸入其憑據的登入表單

pages/login.tsx
import { FormEvent } from 'react'
import { useRouter } from 'next/router'
 
export default function LoginPage() {
  const router = useRouter()
 
  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
 
    const formData = new FormData(event.currentTarget)
    const email = formData.get('email')
    const password = formData.get('password')
 
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    })
 
    if (response.ok) {
      router.push('/profile')
    } else {
      // Handle errors
    }
  }
 
  return (
    <form onSubmit={handleSubmit}>
      <input type="email" name="email" placeholder="Email" required />
      <input type="password" name="password" placeholder="Password" required />
      <button type="submit">Login</button>
    </form>
  )
}

上面的表單有兩個輸入欄位,用於捕獲使用者的電子郵件和密碼。提交時,它會觸發一個函式,該函式向 API 路由 (/api/auth/login) 傳送 POST 請求。

然後,您可以在 API 路由中呼叫身份驗證提供商的 API 來處理身份驗證

pages/api/auth/login.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import { signIn } from '@/auth'
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const { email, password } = req.body
    await signIn('credentials', { email, password })
 
    res.status(200).json({ success: true })
  } catch (error) {
    if (error.type === 'CredentialsSignin') {
      res.status(401).json({ error: 'Invalid credentials.' })
    } else {
      res.status(500).json({ error: 'Something went wrong.' })
    }
  }
}

會話管理

會話管理可確保使用者的身份驗證狀態在請求之間保持不變。它涉及建立、儲存、重新整理和刪除會話或令牌。

有兩種型別的會話:

  1. 無狀態:會話資料(或令牌)儲存在瀏覽器的 cookie 中。每次請求都會發送 cookie,從而允許在伺服器上驗證會話。此方法更簡單,但如果實施不正確,安全性可能會降低。
  2. 資料庫:會話資料儲存在資料庫中,使用者的瀏覽器只接收加密的會話 ID。此方法更安全,但可能很複雜並使用更多的伺服器資源。

須知:雖然您可以使用其中一種方法或兩種方法,但我們建議使用會話管理庫,例如 iron-sessionJose

無狀態會話

設定和刪除 Cookie

您可以使用 API 路由 在伺服器上將會話設定為 cookie

pages/api/login.ts
import { serialize } from 'cookie'
import type { NextApiRequest, NextApiResponse } from 'next'
import { encrypt } from '@/app/lib/session'
 
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const sessionData = req.body
  const encryptedSessionData = encrypt(sessionData)
 
  const cookie = serialize('session', encryptedSessionData, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    maxAge: 60 * 60 * 24 * 7, // One week
    path: '/',
  })
  res.setHeader('Set-Cookie', cookie)
  res.status(200).json({ message: 'Successfully set cookie!' })
}

資料庫會話

要建立和管理資料庫會話,您需要遵循以下步驟:

  1. 在資料庫中建立一個表來儲存會話和資料(或檢查您的身份驗證庫是否處理此問題)。
  2. 實現插入、更新和刪除會話的功能。
  3. 在將會話 ID 儲存到使用者瀏覽器之前對其進行加密,並確保資料庫和 cookie 保持同步(這是可選的,但建議用於 代理 中的樂觀身份驗證檢查)。

在伺服器上建立會話:

pages/api/create-session.ts
import db from '../../lib/db'
import type { NextApiRequest, NextApiResponse } from 'next'
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const user = req.body
    const sessionId = generateSessionId()
    await db.insertSession({
      sessionId,
      userId: user.id,
      createdAt: new Date(),
    })
 
    res.status(200).json({ sessionId })
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' })
  }
}

授權

使用者透過身份驗證並建立會話後,您可以實施授權來控制使用者在應用程式中可以訪問和執行的操作。

有兩種主要的授權檢查型別:

  1. 樂觀:使用儲存在 cookie 中的會話資料檢查使用者是否被授權訪問路由或執行操作。這些檢查對於快速操作非常有用,例如顯示/隱藏 UI 元素或根據許可權或角色重定向使用者。
  2. 安全:使用儲存在資料庫中的會話資料檢查使用者是否被授權訪問路由或執行操作。這些檢查更安全,用於需要訪問敏感資料或操作的操作。

對於這兩種情況,我們建議:

使用代理進行樂觀檢查(可選)

在某些情況下,您可能希望使用 代理 並根據許可權重定向使用者

  • 執行樂觀檢查。由於代理在每個路由上執行,因此它是集中重定向邏輯和預過濾未經授權使用者的好方法。
  • 保護在使用者之間共享資料的靜態路由(例如,付費內容)。

但是,由於代理在所有路由(包括 預取 路由)上執行,因此只從 cookie 中讀取會話(樂觀檢查)非常重要,並且避免資料庫檢查以防止效能問題。

例如

proxy.ts
import { NextRequest, NextResponse } from 'next/server'
import { decrypt } from '@/app/lib/session'
import { cookies } from 'next/headers'
 
// 1. Specify protected and public routes
const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/signup', '/']
 
export default async function proxy(req: NextRequest) {
  // 2. Check if the current route is protected or public
  const path = req.nextUrl.pathname
  const isProtectedRoute = protectedRoutes.includes(path)
  const isPublicRoute = publicRoutes.includes(path)
 
  // 3. Decrypt the session from the cookie
  const cookie = (await cookies()).get('session')?.value
  const session = await decrypt(cookie)
 
  // 4. Redirect to /login if the user is not authenticated
  if (isProtectedRoute && !session?.userId) {
    return NextResponse.redirect(new URL('/login', req.nextUrl))
  }
 
  // 5. Redirect to /dashboard if the user is authenticated
  if (
    isPublicRoute &&
    session?.userId &&
    !req.nextUrl.pathname.startsWith('/dashboard')
  ) {
    return NextResponse.redirect(new URL('/dashboard', req.nextUrl))
  }
 
  return NextResponse.next()
}
 
// Routes Proxy should not run on
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}

雖然代理對初始檢查很有用,但它不應該是保護資料的唯一防線。大多數安全檢查應儘可能靠近資料來源執行,有關更多資訊,請參閱 資料訪問層

提示:

  • 在代理中,您還可以使用 req.cookies.get('session').value 讀取 cookie。
  • 代理使用 邊緣執行時,請檢查您的身份驗證庫和會話管理庫是否相容。
  • 您可以使用代理中的 matcher 屬性來指定代理應在哪些路由上執行。儘管對於身份驗證,建議代理在所有路由上執行。

建立資料訪問層 (DAL)

保護 API 路由

Next.js 中的 API 路由對於處理伺服器端邏輯和資料管理至關重要。保護這些路由以確保只有授權使用者才能訪問特定功能至關重要。這通常涉及驗證使用者的身份驗證狀態及其基於角色的許可權。

以下是保護 API 路由的示例:

pages/api/route.ts
import { NextApiRequest, NextApiResponse } from 'next'
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await getSession(req)
 
  // Check if the user is authenticated
  if (!session) {
    res.status(401).json({
      error: 'User is not authenticated',
    })
    return
  }
 
  // Check if the user has the 'admin' role
  if (session.user.role !== 'admin') {
    res.status(401).json({
      error: 'Unauthorized access: User does not have admin privileges.',
    })
    return
  }
 
  // Proceed with the route for authorized users
  // ... implementation of the API Route
}

此示例演示了具有身份驗證和授權雙層安全檢查的 API 路由。它首先檢查活動會話,然後驗證登入使用者是否為“管理員”。這種方法確保了安全訪問,僅限於經過身份驗證和授權的使用者,從而為請求處理維護了強大的安全性。

資源

現在您已經瞭解了 Next.js 中的身份驗證,以下是 Next.js 相容的庫和資源,可幫助您實現安全的身份驗證和會話管理:

身份驗證庫

會話管理庫

延伸閱讀

要繼續學習身份驗證和安全性,請檢視以下資源: