15
章节15
添加身份验证
在上一章节中,您通过添加表单验证和改进可访问性,完成了发票路由的构建。在本章节中,您将为仪表板添加身份验证。
本章内容...
以下是我们将会涵盖的主题
什么是身份验证。
如何使用 NextAuth.js 为您的应用添加身份验证。
如何使用中间件来重定向用户并保护您的路由。
如何使用 React 的 useActionState
来处理待处理状态和表单错误。
什么是身份验证?
身份验证是当今许多 Web 应用程序的关键组成部分。它是系统检查用户是否是他们所声称身份的方式。
安全的网站通常使用多种方式来检查用户的身份。例如,在输入用户名和密码后,网站可能会向您的设备发送验证码,或使用像 Google Authenticator 这样的外部应用程序。这种双重身份验证 (2FA) 有助于提高安全性。即使有人知道了您的密码,他们也无法在没有您唯一令牌的情况下访问您的帐户。
身份验证 vs. 授权
在 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 上添加环境变量。
添加 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.net.cn/docs/app/building-your-application/routing/middleware#matcher
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};
在这里,您正在使用 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。在本课程中,我们将专注于仅使用凭据提供程序。
凭据提供程序允许用户使用用户名和密码登录。
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
这有帮助吗?