NextAuth.js 官网:https://next-auth.js.org/(Vercel 提供)

其他解决方案:ClerkAuth0(ChatGPT 使用的 Auth 接入方案)、Authing(Auth0 的国产化)

1. 安装依赖:

pnpm add next-auth

2. 新建 app/api/auth/[…nextauth]/route.ts

注释:

  1. Next.js 13.2 以上需要严格将文件路径定义成这样。
  2. 必须要将方法导出为 HTTP 请求名,例如 GET,POST…,否则会报错:

image.png

import NextAuth from "next-auth"

export const authOptions = {
  providers: [],
}
const handler = NextAuth(authOptions)

export {
  handler as GET,
  handler as POST
}

3. 使用 Credentials 做验证:

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"

export const authOptions = {
  providers: [
    CredentialsProvider({
      // The name to display on the sign in form (e.g. 'Sign in with...')
      name: 'Credentials',
      // The credentials is used to generate a suitable form on the sign in page.
      // You can specify whatever fields you are expecting to be submitted.
      // e.g. domain, username, password, 2FA token, etc.
      // You can pass any HTML attribute to the <input> tag through the object.
      credentials: {
        username: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        // You need to provide your own logic here that takes the credentials
        // submitted and returns either a object representing a user or value
        // that is false/null if the credentials are invalid.
        // e.g. return { id: 1, name: 'J Smith', email: '[email protected]' }
        // You can also use the `req` object to obtain additional parameters
        // (i.e., the request IP address)
        if (!credentials) {
          return null
        }
        const { username, password } = credentials
        if (username !== 'PaulChess' || password !== '123456') {
          return null
        }
        return {
          id: '1',
          ...credentials
        }
      }
    })
  ]
}
const handler = NextAuth(authOptions)

export {
  handler as GET,
  handler as POST
}

4. 访问登录路径:http://localhost:3000/api/auth/signin

image.png