npm install next-auth@beta
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
// src/auth.ts import NextAuth from "next-auth" export const config = { providers: [], } export const { handlers, signIn, signOut, auth } = NextAuth(config)
它应该放在src文件夹内
Providers 在 Auth.js 中表示是可用于登录用户的服务。用户可以通过四种方式登录。
https://authjs.dev/reference/nextjs#providers
// src/app/api/auth/[...nextauth]/route.ts import { handlers } from "@/auth" // Referring to the auth.ts we just created export const { GET, POST } = handlers
此文件用于使用 Next.js App Router 设置路由处理程序。
// src/middleware.ts import { auth } from "@/auth" export default auth((req) => { // Add your logic here } export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], // It's default setting }
在src文件夹内写入。
如果写在 src 文件夹之外,中间件将无法工作。
中间件是一个允许您在请求完成之前运行代码的函数。它对于保护路由和处理整个应用程序的身份验证特别有用。
Matcher 是 一个配置选项,用于指定哪些路由中间件应应用于。它有助于仅在必要的路由上运行中间件来优化性能。
示例匹配器: ['/dashboard/:path*'] 仅将中间件应用于仪表板路由。
https://authjs.dev/getting-started/session-management/protecting?framework=express#nextjs-middleware
// src/app/page.tsx import { auth } from "@/auth" import { redirect } from "next/navigation" export default async function page() { const session = await auth() if (!session) { redirect('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) }
// src/app/page.tsx "use client" import { useSession } from "next-auth/react" import { useRouter } from "next/navigation" export default async function page() { const { data: session } = useSession() const router = useRouter() if (!session.user) { router.push('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) } // src/app/layout.tsx import type { Metadata } from "next"; import "./globals.css"; import { SessionProvider } from "next-auth/react" export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body> <SessionProvider> {children} </SessionProvider> </body> </html> ); }
/src /app /api /auth [...nextauth] /route.ts // Route Handler layout.tsx page.tsx auth.ts // Provider, Callback, Logic etc middleware.ts // A function before request
// prisma/schema.prisma model User { id String @id @default(cuid()) name String? email String? @unique emailVerified DateTime? image String? password String? accounts Account[] sessions Session[] } model Account { // ... (standard Auth.js Account model) } model Session { // ... (standard Auth.js Session model) } // ... (other necessary models)
// src/lib/prisma.ts import { PrismaClient } from "@prisma/client" const globalForPrisma = globalThis as unknown as { prisma: PrismaClient } export const prisma = globalForPrisma.prisma || new PrismaClient() if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma
凭据,在身份验证上下文中,指的是使用用户提供的信息验证用户身份的方法,通常是用户名(或电子邮件)和密码。
我们可以在 src/auth.ts 中添加凭据。
npm install next-auth@beta
适配器:
秘密:
页面:
会话:
回调:
jwt 回调:
会话回调:
从 GCP Console 创建新的 OAuth 客户端 ID > API 和服务 >凭证
创建后,保存您的客户端 ID 和客户端密钥以供以后使用。
当我们在本地工作时,设置http://localhost:3000/api/auth/callback/google
生产环境中,只需将 http://localhost:3000 替换为 https://-----即可。
// env.local AUTH_SECRET=GENERATETD_RANDOM_VALUE
// src/auth.ts import NextAuth from "next-auth" export const config = { providers: [], } export const { handlers, signIn, signOut, auth } = NextAuth(config)
https://authjs.dev/getting-started/authentication/oauth
// src/app/api/auth/[...nextauth]/route.ts import { handlers } from "@/auth" // Referring to the auth.ts we just created export const { GET, POST } = handlers
// src/middleware.ts import { auth } from "@/auth" export default auth((req) => { // Add your logic here } export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], // It's default setting }
// src/app/page.tsx import { auth } from "@/auth" import { redirect } from "next/navigation" export default async function page() { const session = await auth() if (!session) { redirect('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) }
// src/app/page.tsx "use client" import { useSession } from "next-auth/react" import { useRouter } from "next/navigation" export default async function page() { const { data: session } = useSession() const router = useRouter() if (!session.user) { router.push('/login') } return ( <div> <h1>Hello World!</h1> <img src={session.user.image} alt="User Avatar" /> </div> ) } // src/app/layout.tsx import type { Metadata } from "next"; import "./globals.css"; import { SessionProvider } from "next-auth/react" export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body> <SessionProvider> {children} </SessionProvider> </body> </html> ); }
/src /app /api /auth [...nextauth] /route.ts // Route Handler layout.tsx page.tsx auth.ts // Provider, Callback, Logic etc middleware.ts // A function before request
// prisma/schema.prisma model User { id String @id @default(cuid()) name String? email String? @unique emailVerified DateTime? image String? password String? accounts Account[] sessions Session[] } model Account { // ... (standard Auth.js Account model) } model Session { // ... (standard Auth.js Session model) } // ... (other necessary models)
以上是在 Next.js App Router 中使用 Auth.js 进行用户身份验证的详细内容。更多信息请关注PHP中文网其他相关文章!