src/lib/plugins/auth/google.ts
Google OAuth 认证插件,支持通过 Google 账号登录。
概述
该插件基于 NextAuth.js 的 Google Provider,集成 Google OAuth 2.0 认证流程。
主要导出
googlePlugin
认证插件实例,实现了 AuthPlugin 接口。
import { googlePlugin } from "@/lib/plugins/auth/google";
功能特性
标准 OAuth 流程
使用 Google 的默认用户资料映射:
- 用户 ID
- 姓名
- 邮箱
- 头像 URL
无需自定义 profile 函数,使用 Google Provider 的默认值。
环境变量
需要配置以下环境变量:
# Google OAuth 2.0 配置
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
获取方式
- 进入 Google Cloud Console
- 创建新项目或选择现有项目
- 启用 Google+ API 或 Google Identity Toolkit API
- 进入 Credentials → Create Credentials → OAuth client ID
- 配置 OAuth 同意屏幕
- 创建 OAuth 2.0 客户端 ID
- 添加授权重定向 URI:
http://localhost:3000/api/auth/callback/google
使用方式
前端登录调用
import { signIn } from "next-auth/react";
await signIn("google");
配置启用
在 prompts.config.ts 中启用:
export default defineConfig({
auth: {
providers: ["google", "credentials"],
allowRegistration: true,
},
// ...
});
用户创建流程
- 用户点击 Google 登录按钮
- 重定向到 Google 授权页面
- 用户授权后,Google 回调到应用
- NextAuth 处理 OAuth 回调
- 调用自定义 Prisma Adapter 创建用户
- 自动生成用户名(基于邮箱或姓名)
注意事项
- Google 不提供用户名(username),由系统自动生成
- 需要验证应用的 OAuth 同意屏幕
- 生产环境需要在 Google Cloud Console 中验证应用
- 确保在 Google Cloud Console 中配置了正确的回调 URL
- 首次登录时会请求访问基本资料信息