01MVP 标识01MVP
开发指南认证系统配置

认证系统配置

Better Auth 配置、OAuth 提供商设置和微信登录集成指南

本页面介绍认证系统的配置和集成步骤。API 使用详情请参考 包文档

概览

项目使用 Better Auth 作为认证框架。

  • 配置位置: apps/mono-web/src/lib/auth/auth.ts
  • 插件目录: apps/mono-web/src/lib/auth/plugins/

环境变量配置

apps/mono-web/.env.local 中添加以下配置:

# Better Auth 基础配置
BETTER_AUTH_SECRET=your-secret-key-min-32-chars
BETTER_AUTH_URL=http://localhost:3000

# 数据库连接
DATABASE_URL=postgresql://user:password@localhost:5432/dbname

支持的登录方式

方式状态配置说明
手机号登录需配置短信服务商
微信扫码(PC)需配置微信开放平台
微信授权(手机)需配置微信公众平台
微信小程序需配置小程序 AppID
邮箱 + 密码默认启用
GitHub OAuth需配置 Client ID/Secret
Google OAuth需配置 Client ID/Secret

微信 OAuth 配置

前置准备

1. 注册微信开放平台账号

访问 微信开放平台 并完成:

  1. 注册开发者账号
  2. 完成开发者资质认证(需要营业执照)
  3. 等待审核通过(通常需要 1-3 个工作日)

2. 创建应用

PC 端 - 网站应用

  1. 在开放平台选择"网站应用"
  2. 填写应用基本信息
  3. 配置授权回调域名:
    # 开发环境
    localhost:3000
    
    # 生产环境
    yourdomain.com
  4. 提交审核,获取 AppIDAppSecret

移动端 - 服务号

  1. 微信公众平台 注册服务号
  2. 完成微信认证(需要支付 300 元认证费)
  3. 在"开发 - 接口权限"中启用"网页授权"
  4. 配置授权回调域名(不需要协议头)
  5. 获取 AppIDAppSecret

小程序

  1. 在微信公众平台注册小程序
  2. 配置业务域名
  3. 获取小程序 AppIDAppSecret

3. 配置 UnionID

为了实现 PC、移动端和小程序账号互通:

  1. 在微信开放平台,将网站应用、服务号和小程序绑定到同一个开放平台账号
  2. 进入"管理中心 - 公众账号/小程序/网站应用"
  3. 将所有应用添加到同一个"应用组"
  4. 绑定后,同一用户在不同应用中会返回相同的 unionid

环境变量配置

# PC 端微信登录(网站应用)
WECHAT_WEBSITE_APP_ID=wx1234567890abcdef
WECHAT_WEBSITE_APP_SECRET=your-website-app-secret

# 移动端微信登录(服务号)
WECHAT_SERVICE_ACCOUNT_APP_ID=wx0987654321fedcba
WECHAT_SERVICE_ACCOUNT_APP_SECRET=your-service-account-secret

# 微信小程序
WECHAT_MINIPROGRAM_APP_ID=wx1234567890abcdef
WECHAT_MINIPROGRAM_APP_SECRET=your-miniprogram-app-secret

服务端集成

项目已在 apps/mono-web/src/lib/auth/auth.ts 中配置好微信 OAuth 插件:

import { wechatOAuth } from "./plugins/wechat-oauth-plugin";

export const auth = betterAuth({
  // ... 其他配置
  plugins: [
    wechatOAuth(), // 自动根据环境变量配置
    // ... 其他插件
  ],
});

创建 Token 交换端点

创建 apps/mono-web/src/app/api/auth/wechat/token/route.ts

import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { code, client_id, client_secret } = body;

    if (!code || !client_id || !client_secret) {
      return NextResponse.json(
        { error: "Missing required parameters" },
        { status: 400 }
      );
    }

    const tokenUrl = new URL("https://api.weixin.qq.com/sns/oauth2/access_token");
    tokenUrl.searchParams.set("appid", client_id);
    tokenUrl.searchParams.set("secret", client_secret);
    tokenUrl.searchParams.set("code", code);
    tokenUrl.searchParams.set("grant_type", "authorization_code");

    const response = await fetch(tokenUrl.toString());
    const data = await response.json();

    if (data.errcode) {
      return NextResponse.json(
        { error: data.errmsg || "WeChat token exchange failed" },
        { status: 400 }
      );
    }

    return NextResponse.json({
      access_token: data.access_token,
      token_type: "Bearer",
      expires_in: data.expires_in,
      refresh_token: data.refresh_token,
      scope: [
        data.scope,
        `openid:${data.openid}`,
        data.unionid ? `unionid:${data.unionid}` : null,
      ].filter(Boolean),
    });
  } catch (error) {
    console.error("WeChat token exchange error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

GitHub OAuth 配置

  1. 访问 GitHub Developer Settings
  2. 创建新的 OAuth App
  3. 配置回调 URL: http://localhost:3000/api/auth/callback/github
  4. 获取 Client ID 和 Client Secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret

Google OAuth 配置

  1. 访问 Google Cloud Console
  2. 创建新项目或选择现有项目
  3. 启用 Google+ API
  4. 创建 OAuth 2.0 凭据
  5. 配置授权回调 URI: http://localhost:3000/api/auth/callback/google
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

Better Auth 插件

项目使用了以下 Better Auth 插件:

  • admin — 管理员角色和权限
  • magic-link — 邮件魔法链接登录
  • openAPI — 自动生成认证相关 OpenAPI 文档
  • organization — 组织管理(角色、邀请)
  • phone-number — 手机号登录
  • two-factor — 双因素认证
  • username — 用户名支持

自定义插件:

  • invitation-only — 仅邀请注册模式
  • wechat-oauth — 微信 OAuth 登录

常见问题

微信回调域名配置错误

问题:登录时提示"redirect_uri 参数错误"

解决方案

  • 检查微信开放平台配置的回调域名是否正确
  • 确保域名不包含协议头(http:// 或 https://)
  • 确保域名不包含端口号(除非是非标准端口)
  • 开发环境可以使用 localhost,但生产环境必须使用已备案的域名

获取不到 UnionID

问题:用户信息中没有 unionid 字段

解决方案

  • 确保网站应用、服务号和小程序已绑定到同一个开放平台账号
  • 检查应用是否在同一个"应用组"中
  • 服务号必须完成微信认证
  • 用户必须关注了服务号(或使用 snsapi_userinfo 授权)

Token 交换失败

问题code 换取 access_token 失败

解决方案

  • 检查 AppIDAppSecret 是否正确
  • 确认 code 是否已过期(5 分钟有效期)
  • 检查 code 是否已被使用(只能使用一次)
  • 确认网络请求是否正常

相关资源