src/lib/plugins/auth/google.ts

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

获取方式

  1. 进入 Google Cloud Console
  2. 创建新项目或选择现有项目
  3. 启用 Google+ API 或 Google Identity Toolkit API
  4. 进入 Credentials → Create Credentials → OAuth client ID
  5. 配置 OAuth 同意屏幕
  6. 创建 OAuth 2.0 客户端 ID
  7. 添加授权重定向 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,
  },
  // ...
});

用户创建流程

  1. 用户点击 Google 登录按钮
  2. 重定向到 Google 授权页面
  3. 用户授权后,Google 回调到应用
  4. NextAuth 处理 OAuth 回调
  5. 调用自定义 Prisma Adapter 创建用户
  6. 自动生成用户名(基于邮箱或姓名)

注意事项

  1. Google 不提供用户名(username),由系统自动生成
  2. 需要验证应用的 OAuth 同意屏幕
  3. 生产环境需要在 Google Cloud Console 中验证应用
  4. 确保在 Google Cloud Console 中配置了正确的回调 URL
  5. 首次登录时会请求访问基本资料信息
← 返回目录