15
章节15
添加认证
在上一章中,你通过添加表单验证和改进可访问性完成了发票路由的构建。在本章中,你将为仪表盘添加身份验证功能。
在本章中...
我们将涵盖以下主题:
什么是身份验证。
如何使用 NextAuth.js 将身份验证添加到你的应用程序。
如何使用中间件重定向用户并保护你的路由。
如何使用 React 的 useActionState 处理挂起状态和表单错误。
什么是身份验证?
身份验证是当今许多 Web 应用程序的关键组成部分。它是系统检查用户是否是其声称的身份的方式。
安全的网站通常会使用多种方式来验证用户的身份。例如,在输入用户名和密码后,网站可能会向你的设备发送验证码,或者使用 Google Authenticator 等外部应用程序。这种双因素身份验证 (2FA) 有助于提高安全性。即使有人知道了你的密码,他们也无法在没有你的唯一令牌的情况下访问你的账户。
身份验证与授权
在 Web 开发中,身份验证和授权扮演着不同的角色
- 身份验证是关于确保用户是他们所说的那个人。你通过拥有的东西(例如用户名和密码)来证明你的身份。
- 授权是下一步。一旦用户的身份得到确认,授权就决定了他们被允许使用应用程序的哪些部分。
因此,身份验证检查你是谁,而授权决定你可以在应用程序中做什么或访问什么。
创建登录路由
首先在你的应用程序中创建一个名为 /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 上添加环境变量。
添加页面选项
在项目根目录创建 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.net.cn/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。
创建一个名为 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。在本课程中,我们将只关注使用 Credentials provider。
Credentials provider 允许用户使用用户名和密码登录。
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。有关选项的完整列表,请参阅 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
这有帮助吗?