Featured image of post NextAuth配置教程

NextAuth配置教程

使用 NextAuth.js 实现认证功能的完整配置指南

NextAuth配置教程

尝试使用Prisma作为数据库适配器,并配置GitHub OAuth和邮箱密码登录。

简述next-auth配置

next-auth是用来给next项目增加认证的,既可以配置邮箱也可以配置GitHub,Google等授权认证,整个使用流程相对简单,而且似乎配置GitHub认证好像其实数据库都可以不要。暂时还处于摸索阶段,勉勉强强配置好了登录,实际上当前配置的逻辑还有点问题,例如GitHub授权后user表中有邮箱,这时候如果邮箱注册会冲突,不过处理起来也还好,暂时先不做了。

关于使用,客户端中提供useSession拿到用户信息,服务端中通过getServerSession获取用户信息。总的来说配置和使用上手难度还是比较容易的。但是配置Google的时候总是报错,测试可能是服务器连不上,但是我开了全局也不行,后面再试试。 image

下面用配置好的代码,用Claude生成了大致的步骤

步骤1: 安装依赖

首先,安装必要的依赖:

1
2
npm install next-auth @prisma/client @next-auth/prisma-adapter bcryptjs
npm install prisma --save-dev

步骤2: 配置环境变量

.env文件中添加以下环境变量:

1
2
3
4
5
DATABASE_URL="your_database_url_here"
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_nextauth_secret_here
GITHUB_ID=your_github_client_id
GITHUB_SECRET=your_github_client_secret

步骤3: 设置Prisma

初始化Prisma并创建数据库schema:

1
npx prisma init

prisma/schema.prisma文件中定义您的模型。这里是一个基本的用户模型示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Account {
  id                 String  @id @default(cuid())
  userId             String
  type               String
  provider           String
  providerAccountId  String
  refresh_token      String?  @db.Text
  access_token       String?  @db.Text
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?  @db.Text
  session_state      String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String    @unique
  password      String?
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

然后,运行以下命令来创建数据库表:

1
npx prisma db push 

步骤4: 创建NextAuth配置文件

创建lib/auth.ts文件并添加以下内容:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import {NextAuthOptions} from "next-auth";
import {PrismaAdapter} from "@next-auth/prisma-adapter";
import {PrismaClient} from "@prisma/client";
import CredentialsProvider from "next-auth/providers/credentials";
import GitHubProvider from "next-auth/providers/github";
import bcrypt from "bcryptjs";

// 创建 Prisma 客户端实例
const prisma = new PrismaClient();

// 定义 NextAuth 的配置选项
export const authOptions: NextAuthOptions = {
    // 使用 Prisma 适配器来处理数据库操作
    adapter: PrismaAdapter(prisma),

    // 配置身份验证提供者
    providers: [
        // 使用邮箱密码的凭证提供者
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                email: {label: "Email", type: "text"},
                password: {label: "Password", type: "password"}
            },
            // 验证用户凭证
            async authorize(credentials) {
                if (!credentials?.email || !credentials?.password) {
                    throw new Error("Missing credentials");
                }
                // 在数据库中查找用户
                const user = await prisma.user.findUnique({
                    where: {email: credentials.email}
                });
                if (!user || !user.password) {
                    throw new Error("User not found");
                }
                // 验证密码
                const isPasswordValid = await bcrypt.compare(credentials.password, user.password);
                if (!isPasswordValid) {
                    throw new Error("Invalid password");
                }
                return user;
            }
        }),
        // GitHub OAuth 提供者
        GitHubProvider({
            clientId: process.env.GITHUB_ID!,
            clientSecret: process.env.GITHUB_SECRET!,
        }),
    ],

    // 自定义认证页面路径
    pages: {
        signIn: '/auth/signin',
        signOut: '/auth/signout',
        error: '/auth/error',
        verifyRequest: '/auth/verify-request',
    },

    // 使用 JWT 策略管理会话
    session: {
        strategy: "jwt",
    },

    // 回调函数配置
    callbacks: {
        // 登录回调
        async signIn({user, account, profile, email, credentials}) {
            try {
                console.log("Sign In Callback:", {user, account, profile, email});

                // 处理 GitHub 登录
                if (account && account.provider === 'github' && profile) {
                    // 查找现有用户
                    const existingUser = await prisma.user.findFirst({
                        where: {
                            OR: [
                                {email: profile.email},
                                {accounts: {some: {providerAccountId: account.providerAccountId}}}
                            ]
                        },
                        include: {accounts: true}
                    });

                    if (existingUser) {
                        // 如果用户存在但没有 GitHub 账号,则添加 GitHub 账号
                        if (!existingUser.accounts.some(acc => acc.provider === 'github')) {
                            await prisma.account.create({
                                data: {
                                    userId: existingUser.id,
                                    type: account.type,
                                    provider: account.provider,
                                    providerAccountId: account.providerAccountId,
                                    access_token: account.access_token,
                                    token_type: account.token_type,
                                    scope: account.scope,
                                }
                            });
                        }
                        return true;
                    }

                    // 如果用户不存在,创建新用户
                    await prisma.user.create({
                        data: {
                            name: profile.name || (profile as any).login || 'Unknown',
                            email: profile.email || `${account.providerAccountId}@github.com`,
                            accounts: {
                                create: {
                                    type: account.type,
                                    provider: account.provider,
                                    providerAccountId: account.providerAccountId,
                                    access_token: account.access_token,
                                    token_type: account.token_type,
                                    scope: account.scope,
                                }
                            }
                        }
                    });
                }

                return true;
            } catch (error) {
                console.error("Error in signIn callback:", error);
                return false;
            }
        },
        // JWT 回调
        async jwt({token, user, account}) {
            if (user) {
                token.id = user.id;
            }
            if (account && account.access_token) {
                token.accessToken = account.access_token;
            }
            return token;
        },
        // 会话回调
        async session({session, token}) {
            if (session.user) {
                (session.user as any).id = token.id as string;
                (session as any).accessToken = token.accessToken;
            }
            return session;
        },
        // 重定向回调
        async redirect({url, baseUrl}) {
            // 允许相对回调 URL
            if (url.startsWith("/")) return `${baseUrl}${url}`
            // 允许同源的回调 URL
            else if (new URL(url).origin === baseUrl) return url
            return baseUrl
        },
    },

    // 认证事件处理
    events: {
        async signIn(message) {
            console.log("User signed in:", message)
        },
        async signOut(message) {
            console.log("User signed out:", message)
        },
        async createUser(message) {
            console.log("User created:", message)
        },
        async linkAccount(message) {
            console.log("Account linked:", message)
        },
        async session(message) {
            console.log("Session created:", message)
        },
    },

    // 开发环境启用调试模式
    debug: process.env.NODE_ENV === 'development',

    // 日志配置
    logger: {
        error(code, metadata) {
            console.error(code, metadata);
        },
        warn(code) {
            console.warn(code);
        },
        debug(code, metadata) {
            console.log(code, metadata);
        },
    },
};

步骤5: 创建API路由

创建app/api/auth/[...nextauth]/route.ts文件:

1
2
3
4
5
6
import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

步骤6: 创建注册API

创建app/api/auth/register/route.ts文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function POST(req: Request) {
    try {
        const { name, email, password } = await req.json();

        const existingUser = await prisma.user.findUnique({ where: { email } });
        if (existingUser) {
            return NextResponse.json({ error: "User already exists" }, { status: 400 });
        }

        const hashedPassword = await bcrypt.hash(password, 10);
        const user = await prisma.user.create({
            data: { name, email, password: hashedPassword },
        });

        return NextResponse.json({ message: "User created successfully" }, { status: 201 });
    } catch (error) {
        console.error("Registration error:", error);
        return NextResponse.json({ error: "An error occurred during registration" }, { status: 500 });
    }
}

步骤7: 创建登录和注册页面

创建app/auth/signin/page.tsxapp/auth/register/page.tsx文件,实现登录和注册表单。

步骤8: 在应用中使用NextAuth

在您的组件中,您可以使用useSession钩子来获取当前会话状态:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { useSession } from "next-auth/react";

export default function Component() {
  const { data: session } = useSession();

  if (session) {
    return <p>Welcome, {session.user.name}!</p>;
  }

  return <p>Please sign in</p>;
}

步骤9: 保护路由

您可以使用getServerSession函数来保护服务器端路由:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";

export default async function ProtectedPage() {
  const session = await getServerSession(authOptions);

  if (!session) {
    return <p>Access Denied</p>;
  }

  return <p>Welcome to the protected page, {session.user.name}!</p>;
}

这就是在Next.js项目中设置和配置NextAuth的基本步骤。根据您的具体需求,您可能需要进行更多自定义配置。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计