添加身份验证
在上一章中,你通过添加表单验证和改进可访问性完成了发票路由的构建。在本章中,你将为仪表板添加身份验证。
在本章中
我们将涵盖以下主题:
- 什么是身份验证?
- 如何使用 NextAuth.js 将身份验证添加到你的应用程序中。
- 如何使用中间件重定向用户并保护你的路由。
- 如何使用 React 的
useActionState来处理挂起状态和表单错误。
什么是身份验证
身份验证是许多现代 Web 应用程序中的关键部分。它是系统用来检查用户是否是他们声称的那个人的方式。
一个安全的网站通常会使用多种方式来验证用户的身份。例如,在输入用户名和密码后,网站可能会向你的设备发送验证码或使用像 Google Authenticator 这样的外部应用。这种双因素身份验证(2FA)有助于提高安全性。即使有人知道了你的密码,如果没有你的唯一令牌,他们仍然无法访问你的账户。
身份验证与授权
在 Web 开发中,身份验证和授权扮演着不同的角色:
- 身份验证 主要是确保用户是他们声称的那个人。你通过像用户名和密码这样的东西来证明你的身份。
- 授权 是下一个步骤。一旦用户的身份得到确认,授权就决定了他们可以使用应用程序的哪些部分。
所以,身份验证检查你是谁,而授权决定你在应用程序中可以做什么或访问什么。
是时候做个小测验了!
以下哪个选项最能描述身份验证和授权之间的区别?
A. 身份验证决定你可以访问什么。授权验证你的身份。 B. 身份验证和授权都决定用户可以访问应用程序的哪些部分。 C. 身份验证验证你的身份。授权决定你可以访问什么。 D. 没有区别,这两个术语的意思是一样的。
创建登录路由
首先在你的应用程序中创建一个名为 /login 的新路由,并粘贴以下代码:
// **/app/login/page.tsx**
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 抽象了管理会话、登录和注销以及身份验证其他方面的复杂性。虽然你可以手动实现这些功能,但过程可能耗时且容易出错。NextAuth.js 简化了这个过程,为 Next.js 应用程序提供了一个统一的身份验证解决方案。
设置 NextAuth.js
通过在终端运行以下命令来安装 NextAuth.js:
pnpm i next-auth@beta
在这里,你正在安装与 Next.js 14 兼容的 NextAuth.js 的 beta 版本。
接下来,为你的应用程序生成一个密钥。这些密钥用于加密 cookie,确保用户会话的安全。你可以通过在终端运行以下命令来生成密钥:
openssl rand -base64 32
然后,在你的 .env 文件中,将生成的密钥添加到 AUTH_SECRET 变量中:
// .env
AUTH_SECRET=your-secret-key
为了确保身份验证在生产环境中正常工作,你还需要在 Vercel 项目中更新你的环境变量。请查看这个指南来了解如何在 Vercel 上添加环境变量。
添加页面选项
在项目根目录下创建一个 auth.config.ts 文件,并导出一个 authConfig 对象。这个对象将包含 NextAuth.js 的配置选项。目前,它只包含 pages 选项:
// **/auth.config.ts**
import type { NextAuthConfig } from 'next-auth';
export const authConfig = {
pages: {
signIn: '/login',
},
} satisfies NextAuthConfig;
你可以使用 pages 选项来指定自定义登录、注销和错误页面的路由。这不是必需的,但通过在 pages 选项中添加 signIn: '/login',用户将被重定向到我们的自定义登录页面,而不是 NextAuth.js 的默认页面。
使用 Next.js 中间件保护你的路由
接下来,添加保护路由的逻辑。这将防止用户在未登录的情况下访问仪表板页面。
// /auth.config.ts
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: [], // 目前添加一个空数组作为 providers
} satisfies NextAuthConfig;
authorized 回调用于通过 Next.js 中间件(Next.js Middleware) 验证请求是否有权访问页面。它在请求完成之前被调用,接收一个包含 auth 和 request 属性的对象。auth 属性包含用户的会话信息,request 属性包含传入的请求信息。
providers 选项是一个数组,用于列出不同的登录选项。现在,它是一个空数组来满足 NextAuth 的配置要求。你将在下面的小节中进一步学习。
接下来,需要将 authConfig 对象导入到一个中间件文件中。在项目根目录下创建一个名为 middleware.ts 的文件,并粘贴以下代码:
// /middleware.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export default NextAuth(authConfig).auth;
export const config = {
// https://nextjs.org/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 对象:
// /auth.ts
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)。
凭证提供程序允许用户使用用户名和密码登录。
// /auth.ts
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 来验证电子邮件和密码,然后检查用户是否存在于数据库中:
// /auth.ts
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 函数,从数据库中查询用户。
// /auth.ts
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('获取用户失败:', error);
throw new Error('获取用户失败。');
}
}
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 来检查密码是否匹配:
// /auth.ts
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('无效的凭证');
return null;
},
}),
],
});
最后,如果密码匹配,你需要返回用户,否则返回 null 以防止用户登录。
更新登录表单
现在,你需要将身份验证逻辑与登录表单连接。在 actions.ts 文件中,创建一个名为 authenticate 的新动作。此动作应从 auth.ts 中导入 signIn 函数:
// /app/lib/actions.ts
'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 '无效的凭证。';
default:
return '出现了一个错误。';
}
}
throw error;
}
}
如果发生 'CredentialsSignin' 错误,你需要显示适当的错误信息。你可以在 NextAuth.js 文档 中找到所有可能的错误类型。
最后,在你的 login-form.tsx 组件中,你可以使用 React 的 useActionState 来调用服务器动作,处理表单错误,并显示表单的加载状态:
// app/ui/login-form.tsx
'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 函数:
// /ui/dashboard/sidenav.tsx
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>
);
}
试试看
现在,试试看。你应该可以使用以下凭据登录和注销应用程序:
- Email:
user@nextmail.com - Password:
123456