在前一章中,您通过添加表单验证和改进可访问性,完成了发票路由的构建。在本章中,你将为dashboard添加身份验证。
在本章中,你将学到……
- 什么是身份验证?
- 如何使用 NextAuth.js 为应用程序添加身份验证功能。
- 如何使用中间件重定向用户并保护路由。
- 如何使用 React 的
useFormStatus和useFormState来处理待处理状态和表单错误。
什么是身份验证?
身份验证是当今许多网络应用程序的关键部分。它是系统检查用户身份的方式。
安全网站通常使用多种方式检查用户身份。例如,在输入用户名和密码后,网站可能会向您的设备发送验证码,或使用 Google Authenticator 等外部应用程序。这种双因素身份验证(2FA)有助于提高安全性。即使有人知道了您的密码,如果没有您的唯一令牌,他们也无法访问您的账户。
认证与授权
在网络开发中,身份验证和授权扮演着不同的角色:
- 身份验证是为了确保用户的真实身份。你需要用用户名和密码等信息来证明自己的身份。
- 授权是下一步。一旦用户的身份得到确认,授权将决定他们可以使用应用程序的哪些部分。
因此,身份验证检查你是谁,而授权则决定你在应用程序中可以做什么或访问什么。
创建登录路径
首先,在应用程序中创建名为 /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:
npm install next-auth@beta
在此,您将安装 beta 版本的 NextAuth.js,它与 Next.js 14 兼容。
接下来,为您的应用程序生成一个密钥。该密钥用于加密 cookie,确保用户会话的安全性。您可以在终端运行以下命令来生成密钥:
openssl rand -base64 32
然后,在 .env 文件中,将生成的密钥添加到 AUTH_SECRET 变量中:
.env
AUTH_SECRET=your-secret-key
要让 auth 在生产中正常工作,还需要更新 Vercel 项目中的环境变量。查看本指南,了解如何在 Vercel 上添加环境变量。
添加页面选项
在项目根目录下创建一个 auth.config.ts 文件,导出一个 authConfig 对象。该对象将包含 NextAuth.js 的配置选项。目前,它只包含 pages 选项:
/auth.config.ts
import type { NextAuthConfig } from 'next-auth';
export const authConfig = {
pages: {
signIn: '/login',
},
};
您可以使用 pages 选项指定自定义登录、退出和错误页面的路径。这不是必需的,但通过在 pages 选项中添加 signIn: '/login' ,用户将被重定向到我们的自定义登录页面,而不是 NextAuth.js 的默认页面。
使用Next.js中间件保护路由
接下来,添加保护路由的逻辑。这将防止用户访问dashboard页面,除非他们已登录。
/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; // 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 的文件,并粘贴以下代码:
/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 属性。你还使用了 Middleware 中的 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。在本课程中,我们将只专注于使用凭据提供程序。
凭据提供程序允许用户使用用户名和密码登录。
/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 或电子邮件提供程序。有关选项的完整列表,请参阅 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('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 检查密码是否匹配:
/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('Invalid credentials');
return null;
},
}),
],
});
最后,如果密码匹配,则返回用户,否则返回 null 以阻止用户登录。
更新登录表格
现在,您需要将认证逻辑与登录表单连接起来。在您的 actions.ts 文件中,创建一个名为 authenticate 的新操作。此操作应从 auth.ts 中导入 signIn 函数:
/app/lib/actions.ts
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 的 useFormState 来调用服务器操作和处理表单错误,并使用 useFormStatus 来处理表单的待处理状态:
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 { useFormState, useFormStatus } from 'react-dom';
import { authenticate } from '@/app/lib/actions';
export default function LoginForm() {
const [errorMessage, dispatch] = useFormState(authenticate, undefined);
return (
<form action={dispatch} 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>
<LoginButton />
<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>
);
}
function LoginButton() {
const { pending } = useFormStatus();
return (
<Button className="mt-4 w-full" aria-disabled={pending}>
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
</Button>
);
}
添加注销功能
要在 <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