安装 Auth.js
首先为你的框架安装相应的 Auth.js 软件包。
npm install next-auth@beta没有必要安装 @auth/core,因为作为使用者,你应该永远不会直接
使用 @auth/core 软件包。
环境设置
唯一必须设置的环境变量是 AUTH_SECRET。这是一个随机值,用于加密令牌(tokens)和电子邮件
验证哈希值。(详情请参见 部署 章节)。你可以通过运行官方提供的 Auth.js 命令行工具 自动生成一个:
npx auth secret上述命令还会将生成的随机值添加到您的 .env 文件中,并遵守所用框架约定(例如:Next.js’ 是 .env.local 文件)。
配置
Next, create the Auth.js config file and object. This is where you can control the behaviour of the library and specify custom authentication logic, adapters, etc. We recommend all frameworks to create an auth.ts file in the project. In this file we’ll pass in all the options to the framework specific initialization function and then export the route handler(s), signin and signout methods, and more.
其实你可以给这个文件起任何你想要的名字,也可以把它放在任何你喜欢的地方, 但上面这些都是我们经过实践所形成的惯例。
- 首先,在应用程序根目录下创建一个新的
auth.ts文件,内容如下。
import NextAuth from "next-auth"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [],
})- 在
/app/api/auth/[...nextauth]/route.ts文件中添加路由处理程序。
该文件必须是 app/ 路由器的路由处理程序,但应用程序的其他部分
可以放在 page/ 目录下。
import { handlers } from "@/auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers- 添加可选的中间件以保持会话有效,每次调用时都会更新会话过期时间。
export { auth as middleware } from "@/auth"设置身份验证方法
经过上述步骤,基本设置就完成了!接下来,我们将设置第一个身份验证方法,并填入 providers 数组。