NestJS中文文档
教程 / 为 Node.js API 添加 Google 登录
已译 191/191

为 Node.js API 添加 Google 登录

在 TypeScript 中用 NestJS 为 Node.js API 添加「使用 Google 登录」:校验 Google ID 令牌,安全地关联账号,并签发 API 自己的 JWT。

使用 JWT 认证构建 REST API 中的笔记 API 使用密码让用户登录。本教程添加 Google:Web 或移动应用从 Google 的登录库获取 ID 令牌,API 校验它,并像密码登录那样返回相同的访问令牌和刷新令牌。校验是容易的部分。困难的部分是判断一次 Google 登录属于哪个账号。

完成本教程后,这个 API 将能够:

  • 使用 @nestjs/authentication 的 JwtVerifier 校验 Google ID 令牌:对照 Google 公布的密钥校验签名,并校验签发者、受众和有效期。
  • 在首次登录时创建一个账号,此后通过 Google 为该账号分配的 id 找到它,而绝不通过邮箱。
  • 绝不把密码账号交给任何用其邮箱通过 Google 登录的人,而是让账号所有者主动关联 Google。
  • 绝不断开某个账号的最后一种登录方式。
  • 针对 PostgreSQL 和一个 Google 的替身,证明十次并发的首次登录只会创建一个账号。

本教程添加的端点如下:

端点 小节
POST /auth/google 使用 Google ID 令牌登录
GET /me/identities、POST /me/identities/google、DELETE /me/identities/google 将 Google 关联到已有账号
提示

完成后的应用位于 GitHub:nestjs/example-google-login,其中包含测试和 CI 工作流。

从笔记 API 开始

本教程延续 JWT 教程完成后的应用,包括笔记:用户登录正是为了使用它们。如果你已经构建过,就在该项目及其数据库中继续工作。否则,使用 JWT 教程的包创建项目:

$ npm i -g @nestjs/cli
$ nest new notes-api --minimal
$ cd notes-api
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/throttler @nestjs/swagger @nestjs/terminus
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite @electric-sql/pglite

然后从完成后的 JWT 教程中原样取得以下内容:

  • 整个 src/(包括 src/notes/)以及整个 test/
  • 带有两个迁移的 drizzle/ 文件夹、drizzle.config.ts 和 vitest.config.e2e.ts
  • package.json 中的 test:e2e 脚本,以及包含 DATABASE_URL 和 JWT_SECRET 的 .env(用于 JWT 教程的 PostgreSQL 容器)

保留这些迁移:本教程会向同一个数据库添加第三个迁移。在新的数据库上,先应用它们。如果 drizzle-kit 回答某个 snapshot.json「不是最新版本」,说明这些迁移是由它较旧的候选发布版本生成的:drizzle-kit up 会升级它们。

$ npx drizzle-kit up
$ npx drizzle-kit migrate

API 的 Google 登录如何工作

Google 的库在客户端完成用户登录:Web 上使用 Google Identity Services,Android 上使用 Credential Manager,iOS 上使用 Google Sign-In。这些库交给客户端一个 ID 令牌:一个由 Google 签名的 JWT,其中指明了 Google 账号(sub)、其邮箱、Google 是否已验证该邮箱(email_verified),以及令牌签发给的 OAuth 客户端(aud)。客户端把它发送给 API 一次,之后使用 API 的令牌。API 只获取 Google 的公钥,不需要客户端密钥。

提示

用会话 Cookie 保持用户登录的服务端渲染 Web 应用,更适合使用认证章节的重定向流程,即浏览器前往 Google 再返回。它始终通过会话登录,因此这个使用 Bearer 令牌的 API 不采用该流程。

配置 Google OAuth 客户端

ID 令牌会签发给你在 Google Cloud 控制台中的某个 OAuth 客户端:

  1. 在 Google Auth Platform 中填写 Branding 页面:应用名称、支持邮箱、你的主页和隐私政策。
  2. 在 Clients 页面上创建一个类型为 Web application 的客户端。
  3. 在 Authorized JavaScript origins 下添加展示该按钮的 Web 应用的来源,例如 https://app.example.com。本地开发时,添加 http://localhost 和 http://localhost:5173 两者,端口用你 Web 应用的端口。按钮通过 JavaScript 回调,因此不需要重定向 URI。
  4. 复制客户端 ID,它以 .apps.googleusercontent.com 结尾。API 不需要密钥。

移动应用在同一个项目中拥有自己的客户端,正如 Google 针对各平台的指南所述。Android 的 Credential Manager 为 web 客户端 ID 请求令牌(setServerClientId()),因此这些令牌把 Web 客户端作为其受众。如果你的应用的令牌还签发给了其他客户端 ID,请把它们与 Web 客户端一起列出。

警告

本教程在没有真实 Google 登录的情况下编写和测试。下文每个 ID 令牌都由一个 Google 的替身签名,带有 Google 的声明,与测试中相同。控制台步骤遵循编写时 Google 的文档。校验器也针对 Google 的真实密钥集运行过,后者拒绝了替身的令牌。

客户端 ID 写入 .env,以逗号分隔:

# API 接受其 ID 令牌的所有 OAuth 客户端:先是 Web 客户端,然后是任何移动客户端。
GOOGLE_CLIENT_IDS=1234567890-web.apps.googleusercontent.com

配置 schema 要求至少一个,因此缺少 ID 会让应用在启动时停止。Google 密钥的 URL 有默认值,只有测试会修改它:

src/config.ts
// ...
export const envSchema = z.object({
  // ...
  // API 接受其 Google ID 令牌的 OAuth 客户端 ID,以逗号分隔。
  GOOGLE_CLIENT_IDS: z
    .string()
    .transform((value) => value.split(',').map((id) => id.trim()).filter(Boolean))
    .pipe(z.array(z.string()).min(1)),
  // Google 的签名密钥。测试会提供自己的密钥。
  GOOGLE_JWKS_URL: z.url().default('https://www.googleapis.com/oauth2/v3/certs'),
});
// ...

存储身份,而不是邮箱

Google 通过 sub 声明标识一个账号,该值永不重用。账号的邮箱可能改变,某个地址以后也可能属于另一个 Google 账号。因此 Google 账号与用户之间的关联自成一列,以提供者以及该提供者为账号分配的 id 为键。由 Google 创建的用户没有密码:

src/database/schema.ts
import { boolean, index, jsonb, pgTable, primaryKey, text, timestamp, unique, uuid } from 'drizzle-orm/pg-core';

const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  // 使用 Google 登录创建的账号为 null。
  passwordHash: text('password_hash'),
  createdAt: at('created_at').notNull().defaultNow(),
});

// 在其他提供者处让用户登录的账号,通过该提供者为账号分配的 id 找到。
export const identities = pgTable(
  'identities',
  {
    provider: text('provider').notNull(),
    // Google 的 `sub`:在 Google 账号的整个生命周期内稳定,不像其邮箱。
    subject: text('subject').notNull(),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    // 提供者报告的地址,仅用于展示。
    email: text('email'),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [
    // 每个提供者账号只对应一个用户:两次首次登录无法创建两个用户。
    primaryKey({ columns: [table.provider, table.subject] }),
    // 每个用户在每个提供者处只对应一个账号。
    unique('identities_user_id_provider_key').on(table.userId, table.provider),
  ],
);

// ...
export type Note = typeof notes.$inferSelect;
export type Identity = typeof identities.$inferSelect;

主键意味着无论代码怎么写,PostgreSQL 都不会让一个 Google 账号登录两个用户。唯一约束让每个用户至多拥有一个 Google 账号,因此 DELETE /me/identities/google 指向唯一一条关联。identities 中的邮箱只用于向用户展示关联的是哪个账号;不会用它做任何查找。

生成迁移并应用它。它让 password_hash 可为空并创建表;现有用户保留他们的密码:

$ npx drizzle-kit generate --name=identities
$ npx drizzle-kit migrate

users 仓储通过身份查找用户,并在一个事务中连同身份一起创建 Google 用户:

src/users/users.repository.ts
import { and, eq } from 'drizzle-orm';
import { identities, users } from '../database/schema.js';
// ...

  /** 仅用于密码登录。用 Google 创建的账号,`passwordHash` 为 null。 */
  async findCredentials(email: string): Promise<{ user: User; passwordHash: string | null } | null> {
    // ...
  }

  /** 提供者账号登录到的用户。 */
  async findByIdentity(provider: string, subject: string): Promise<User | null> {
    const [user] = await this.db
      .select(columns)
      .from(identities)
      .innerJoin(users, eq(users.id, identities.userId))
      .where(and(eq(identities.provider, provider), eq(identities.subject, subject)));
    return user ?? null;
  }

  /** 没有密码的新用户,关联到某个提供者的账号;邮箱被占用时为 `null`。 */
  createWithIdentity(email: string, provider: string, subject: string): Promise<User | null> {
    return this.db.transaction(async (tx) => {
      // 同一个邮箱的并发插入会让这里等待那个事务,
      // 如果那个事务已提交,这里就什么都不插入。
      const [user] = await tx
        .insert(users)
        .values({ email: normalize(email) })
        .onConflictDoNothing({ target: users.email })
        .returning(columns);
      if (!user) {
        return null;
      }
      await tx.insert(identities).values({ provider, subject, userId: user.id, email });
      return user;
    });
  }

邮箱被占用时,ON CONFLICT DO NOTHING 不返回任何行,由调用方决定其含义。而唯一约束冲突会中止事务,并返回 500。

没有密码的用户绝不能使用密码登录。PasswordHasher.verify() 已经处理了哈希缺失的情况:它会校验一个假的哈希并返回 false,与未知邮箱时相同。CredentialsService.verify() 只需要补上 TypeScript 现在要求的检查:

src/auth/credentials.service.ts
  async verify(email: string, password: string): Promise<User | null> {
    const found = await this.usersRepository.findCredentials(email);
    // 没有账号时,verify() 会校验一个假哈希,因此响应时间
    // 不会泄露哪些邮箱已注册。
    // 用 Google 创建的账号没有密码,情况相同。
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    if (!valid || !found?.passwordHash) {
      return null;
    }
    // ...
  }

对 Google 账号进行密码登录,与对无人注册的地址登录一样,得到相同的 401,耗时也相同。

校验 Google ID 令牌

Google 以 JSON Web Key Set(JWKS)的形式公布其签名密钥。JwksClient 获取并缓存它,当令牌指明了它不认识的密钥时(Google 会轮换密钥)重新获取。JwtVerifier 对照它校验签名,以及签发者、受众和有效期。它正是 JwtBearerProvider 用于其他签发者令牌的校验器(参见向移动应用签发令牌):

src/auth/google-id-token.verifier.ts
import { Injectable, Logger, ServiceUnavailableException, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwksClient, JwtError, JwtVerifier } from '@nestjs/authentication';
import type { Env } from '../config.js';

/** API 从已校验的 Google ID 令牌中取用的内容。 */
export interface GoogleAccount {
  /** Google 为该账号分配的 id:稳定,永不重用。 */
  subject: string;
  email?: string;
  /** Google 是否已验证该账号拥有 `email`。 */
  emailVerified: boolean;
}

// Google 为其 ID 令牌记录了 `iss` 的两种取值。
const GOOGLE_ISSUERS = ['https://accounts.google.com', 'accounts.google.com'];

@Injectable()
export class GoogleIdTokenVerifier {
  private readonly logger = new Logger(GoogleIdTokenVerifier.name);
  private readonly verifier: JwtVerifier;

  constructor(config: ConfigService<Env, true>) {
    this.verifier = new JwtVerifier({
      jwks: new JwksClient(config.get('GOOGLE_JWKS_URL', { infer: true })),
      // 令牌必须指明其中之一。
      issuer: GOOGLE_ISSUERS,
      // 签发给 Google 任何其他客户端的令牌都会被拒绝。
      audience: config.get('GOOGLE_CLIENT_IDS', { infer: true }),
      required: ['exp', 'sub'],
      // Google 的时钟与本服务器的时钟从不完全相同。
      clockTolerance: '30s',
    });
  }

  async verify(idToken: string): Promise<GoogleAccount> {
    try {
      const claims = await this.verifier.verify(idToken);
      return {
        subject: claims.sub!,
        email: typeof claims.email === 'string' ? claims.email : undefined,
        emailVerified: claims.email_verified === true,
      };
    } catch (error) {
      if (error instanceof JwtError) {
        throw new UnauthorizedException(`Invalid Google ID token: ${error.message}`);
      }
      // 无法获取 Google 的密钥:不是客户端的过错,值得重试。
      this.logger.error('Google ID token verification failed', error);
      throw new ServiceUnavailableException('Google sign-in is unavailable');
    }
  }
}
  • 受众就是你的客户端 ID。 Google 用相同的密钥为每个应用的 ID 令牌签名。如果不做这项检查,用户浏览器交给另一个网站的令牌也能在这里让他们登录,因此 JwtVerifier 拒绝没有 audience 的 jwks。
  • Google 的两个签发者。 Google 把 https://accounts.google.com 和 accounts.google.com 都记录为 ID 令牌的 iss。issuer 选项接受它认可的值组成的列表(在 @nestjs/authentication 0.1.8 及更高版本中),指明任何其他签发者的令牌都会被拒绝。
  • 令牌有问题返回 401,服务中断返回 503。 JwtError 说明令牌失败的原因。无法获取 Google 的密钥时,客户端应该稍后重试,而不是让用户退出登录。
提示

ID 令牌大约有效一小时,在此期间任何复制到它的人都能在这里兑换它。Google 的库会把你的 nonce 放进令牌(Web 的 initialize() 调用的 nonce 选项,Android 上的 setNonce())。一个每次登录都签发随机 nonce 且每个只接受一次的 API 可以阻止重放;verify() 返回所有声明,因此这项检查就是比较 claims.nonce。它需要自己的端点和表,因此本教程略去。

使用 Google ID 令牌登录

校验通过的令牌会导向三种情况之一:该 Google 账号已经关联到某个用户;尚未关联且其地址未被占用;尚未关联但该地址属于某个账号:

src/auth/google-sign-in.service.ts
import { ConflictException, ForbiddenException, Injectable } from '@nestjs/common';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';
import type { GoogleAccount } from './google-id-token.verifier.js';

@Injectable()
export class GoogleSignInService {
  constructor(private readonly usersRepository: UsersRepository) {}

  /** Google 账号登录到的用户,在首次登录时创建。 */
  async signIn(google: GoogleAccount): Promise<User> {
    const linked = await this.usersRepository.findByIdentity('google', google.subject);
    if (linked) {
      return linked;
    }
    // 首次登录。邮箱会成为账号的邮箱,因此必须是 Google 验证过的。
    if (!google.email || !google.emailVerified) {
      throw new ForbiddenException('Google has not verified the email address of this account');
    }
    const created = await this.usersRepository.createWithIdentity(google.email, 'google', google.subject);
    if (created) {
      return created;
    }
    // 邮箱已被占用。使用该 Google 账号的一次并发首次登录可能刚刚占用了它,
    // 那样的话那个用户就是这一个。
    const raced = await this.usersRepository.findByIdentity('google', google.subject);
    if (raced) {
      return raced;
    }
    // 有人用这个邮箱和密码注册了。现在关联会让他们也能登录。
    throw new ConflictException({
      message: 'An account with this email exists: sign in with its password, then connect Google',
      error: 'Conflict',
      statusCode: 409,
      errorCode: 'link_required',
    });
  }
}

再次登录的 Google 账号,无论其邮箱现在显示什么,都会登录到它对应的用户。首次登录只会用 Google 验证过的地址创建用户;未验证的地址可能属于别人,因此会得到 403。

防止账号预劫持

在这里,按地址关联会把账号交给攻击者,因为 JWT 教程从不检查用户是否拥有他们注册时使用的地址。有人先用 ada@gmail.com 和一个自选的密码注册。当 Ada 之后用 Google 登录时,她会落入那个账号,把笔记存在里面,而攻击者仍然掌握着密码。这就是账号预劫持。

因此那次登录会得到 409,errorCode 为 link_required:客户端要求用户先用密码登录,然后再关联 Google。这个回答会暴露该地址拥有账号,但只有 Google 为其验证过该地址的人才能看到。如果所有者从未设置那个密码,那就是别人设置的,而密码重置能把账号还给他们。一个验证邮箱地址的 API 可以关联双方都验证过同一地址的账号,认证章节就是这样做的。

两次首次登录同时发生

一次双击会为一个 Google 账号发出两次首次登录。两者都找不到身份,并插入一个相同邮箱的用户;PostgreSQL 让第二次插入等待第一个事务,然后不插入任何内容。第二个请求再次读取身份,并登录到第一个请求创建的用户。如果没有这次读取,它会返回 409,就好像某个陌生人拥有该地址。

路由

请求体以 credential 携带 ID 令牌,这是 Google 的 Web 库使用的名称:

src/auth/auth.schemas.ts
// ...
// Google 的登录库交给客户端的东西:一个签名的 JWT,略高于 1 KB。
const credential = z.string().min(1).max(4096);

export const googleSignInSchema = z.object({ credential });
export type GoogleSignInDto = z.infer<typeof googleSignInSchema>;

export const connectGoogleSchema = z.object({ credential, password: z.string().max(128) });
export type ConnectGoogleDto = z.infer<typeof connectGoogleSchema>;

控制器校验令牌、找到用户,并用 TokenService 签发令牌,与 POST /auth/token 相同:

src/auth/google-auth.controller.ts
import { Body, Controller, HttpCode, Post } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { Throttle, minutes } from '@nestjs/throttler';
import { googleSignInSchema, type GoogleSignInDto } from './auth.schemas.js';
import { GoogleIdTokenVerifier } from './google-id-token.verifier.js';
import { GoogleSignInService } from './google-sign-in.service.js';

@Public()
@ApiSecurity({})
@Controller('auth/google')
export class GoogleAuthController {
  constructor(
    private readonly googleIdTokenVerifier: GoogleIdTokenVerifier,
    private readonly googleSignInService: GoogleSignInService,
    private readonly tokenService: TokenService,
  ) {}

  // 与 POST /auth/token 相同的令牌,只是换成 Google ID 令牌。
  @Throttle({ default: { limit: 30, ttl: minutes(15) } })
  @Post()
  @HttpCode(200)
  async signIn(@Body({ schema: googleSignInSchema }) body: GoogleSignInDto) {
    const google = await this.googleIdTokenVerifier.verify(body.credential);
    const user = await this.googleSignInService.signIn(google);
    return this.tokenService.issue(user.id, { method: 'oidc:google' });
  }
}

令牌是 API 自己的,因此笔记路由和 POST /auth/token/refresh 不关心用户是如何登录的。该路由有自己的限流,因为 account 额度按请求体中的邮箱计数,而这个请求体没有邮箱。ID 令牌是一种凭据,因此把 credential 加入 main.ts 中日志记录器的 redact 列表:

src/main.ts
// ...
  logger: new ConsoleLogger({
    // ...
    redact: ['password', 'authorization', 'accessToken', 'refreshToken', 'credential'],
  }),
// ...

模块注册见下一节。

将 Google 关联到已有账号

已登录的用户从账号页面关联 Google:Web 应用显示同一个按钮,并把 ID 令牌发送到 POST /me/identities/google。不需要匹配邮箱,因为访问令牌证明了账号,ID 令牌证明了 Google 账号。之所以要密码:关联会增加一种持久的登录方式,而被盗的访问令牌即便在其 15 分钟有效期内,也不应足以添加窃贼的 Google 账号。仓储负责列出、关联和解除关联:

src/users/identities.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq, exists, isNotNull } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { identities, users, type Identity } from '../database/schema.js';

export type ConnectedAccount = Pick<Identity, 'provider' | 'email' | 'createdAt'>;

const columns = { provider: identities.provider, email: identities.email, createdAt: identities.createdAt };

/** 关联到某个用户的提供者账号。 */
@Injectable()
export class IdentitiesRepository {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  list(userId: string): Promise<ConnectedAccount[]> {
    return this.db.select(columns).from(identities).where(eq(identities.userId, userId)).orderBy(asc(identities.provider));
  }

  /** 提供者账号属于谁:它关联到的用户,或 `undefined`。 */
  async ownerOf(provider: string, subject: string): Promise<string | undefined> {
    const [row] = await this.db
      .select({ userId: identities.userId })
      .from(identities)
      .where(and(eq(identities.provider, provider), eq(identities.subject, subject)));
    return row?.userId;
  }

  /** 是否建立了关联:当该提供者账号、或该用户在该提供者处的账号已经关联时,不建立。 */
  async link(userId: string, provider: string, subject: string, email?: string): Promise<boolean> {
    // 由约束决定,因此同一个账号的两次并发关联中只有一次成功。
    const linked = await this.db
      .insert(identities)
      .values({ userId, provider, subject, email })
      .onConflictDoNothing()
      .returning({ provider: identities.provider });
    return linked.length > 0;
  }

  /** 是否移除了关联。绝不移除用户的最后一种登录方式:没有密码的用户会保留它。 */
  async unlink(userId: string, provider: string): Promise<boolean> {
    const hasPassword = this.db
      .select({ id: users.id })
      .from(users)
      .where(and(eq(users.id, userId), isNotNull(users.passwordHash)));
    // 一条语句:检查与删除无法被另一个请求插入其间。
    const removed = await this.db
      .delete(identities)
      .where(and(eq(identities.userId, userId), eq(identities.provider, provider), exists(hasPassword)))
      .returning({ provider: identities.provider });
    return removed.length > 0;
  }
}

UsersModule 提供它,并连同 UsersRepository 一起导出:

src/users/users.module.ts
import { Module } from '@nestjs/common';
import { IdentitiesRepository } from './identities.repository.js';
import { MeController } from './me.controller.js';
import { UsersRepository } from './users.repository.js';

@Module({
  controllers: [MeController],
  providers: [UsersRepository, IdentitiesRepository],
  exports: [UsersRepository, IdentitiesRepository],
})
export class UsersModule {}

服务校验密码,并把语句改动的结果转化为回答:

src/auth/identities.service.ts
import { ConflictException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import type { User } from '../users/user.js';
import { IdentitiesRepository } from '../users/identities.repository.js';
import { CredentialsService } from './credentials.service.js';
import type { GoogleAccount } from './google-id-token.verifier.js';

@Injectable()
export class IdentitiesService {
  constructor(
    private readonly identitiesRepository: IdentitiesRepository,
    private readonly credentialsService: CredentialsService,
  ) {}

  /** 把一个 Google 账号关联到已确认密码的已登录用户。 */
  async connectGoogle(user: User, password: string, google: GoogleAccount): Promise<void> {
    if (!(await this.credentialsService.verify(user.email, password))) {
      throw new ForbiddenException('Wrong password');
    }
    if (await this.identitiesRepository.link(user.id, 'google', google.subject, google.email)) {
      return;
    }
    // 未关联:该 Google 账号已属于这个用户(重试)、属于别人,
    // 或者这个用户已有另一个。
    const owner = await this.identitiesRepository.ownerOf('google', google.subject);
    if (owner !== user.id) {
      throw new ConflictException(
        owner ? 'This Google account is connected to another account' : 'Disconnect your other Google account first',
      );
    }
  }

  async disconnectGoogle(userId: string): Promise<void> {
    if (await this.identitiesRepository.unlink(userId, 'google')) {
      return;
    }
    const accounts = await this.identitiesRepository.list(userId);
    if (!accounts.some(({ provider }) => provider === 'google')) {
      throw new NotFoundException('Google is not connected');
    }
    throw new ConflictException('Google is the only way to sign in to this account');
  }
}
  • 由插入来决定。 两个用户同时关联同一个 Google 账号时,如果先读再检查,两者都会通过;主键让其中一次插入成功。插入被拒之后的读取只用于挑选回答。
  • 密码错误返回 403。 401 会告诉客户端其访问令牌有问题,并让用户退出登录。
  • 最后一种登录方式会保留。 对没有密码的用户解除 Google 关联会把他们锁在自己的笔记之外。该条件属于 DELETE 的一部分,因此其间不会发生变化,这样的用户会得到 409。

该控制器位于全局认证守卫之后,与 GET /me 一样:

src/auth/identities.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Throttle, minutes } from '@nestjs/throttler';
import type { User } from '../users/user.js';
import { IdentitiesRepository } from '../users/identities.repository.js';
import { connectGoogleSchema, type ConnectGoogleDto } from './auth.schemas.js';
import { GoogleIdTokenVerifier } from './google-id-token.verifier.js';
import { IdentitiesService } from './identities.service.js';

@Controller('me/identities')
export class IdentitiesController {
  constructor(
    private readonly identitiesRepository: IdentitiesRepository,
    private readonly googleIdTokenVerifier: GoogleIdTokenVerifier,
    private readonly identitiesService: IdentitiesService,
  ) {}

  @Get()
  list(@CurrentUser('id') userId: string) {
    return this.identitiesRepository.list(userId);
  }

  // 它会校验密码,因此像登录一样限流。
  @Throttle({ default: { limit: 5, ttl: minutes(15) } })
  @Post('google')
  @HttpCode(204)
  async connect(@CurrentUser() user: User, @Body({ schema: connectGoogleSchema }) body: ConnectGoogleDto) {
    const google = await this.googleIdTokenVerifier.verify(body.credential);
    await this.identitiesService.connectGoogle(user, body.password, google);
  }

  @Delete('google')
  @HttpCode(204)
  disconnect(@CurrentUser('id') userId: string) {
    return this.identitiesService.disconnectGoogle(userId);
  }
}

在 AuthModule 中注册这两个控制器和新的提供者:

src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { AuthController } from './auth.controller.js';
import { CredentialsService } from './credentials.service.js';
import { DrizzleRefreshTokenStore } from './drizzle-refresh-token.store.js';
import { GoogleAuthController } from './google-auth.controller.js';
import { GoogleIdTokenVerifier } from './google-id-token.verifier.js';
import { GoogleSignInService } from './google-sign-in.service.js';
import { IdentitiesController } from './identities.controller.js';
import { IdentitiesService } from './identities.service.js';
import { JwtAuth } from './jwt-auth.provider.js';

@Module({
  imports: [UsersModule],
  controllers: [AuthController, GoogleAuthController, IdentitiesController],
  providers: [
    JwtAuth,
    CredentialsService,
    DrizzleRefreshTokenStore,
    GoogleIdTokenVerifier,
    GoogleSignInService,
    IdentitiesService,
  ],
})
export class AuthModule {}

添加「使用 Google 登录」按钮

在 Web 上,Google Identity Services 渲染按钮、让用户登录,并用 ID 令牌调用你的函数。Web 应用的一个最小页面把它发送到 API:

web/index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Notes: sign in</title>
    <script src="https://accounts.google.com/gsi/client" async></script>
  </head>
  <body>
    <div id="google-button"></div>
    <p id="status"></p>
    <script>
      const API_URL = 'http://localhost:3000';
      const GOOGLE_CLIENT_ID = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com';
      const status = document.getElementById('status');

      // 用户选择账号后,Google 会以 `credential` 的形式用 ID 令牌调用这里。
      async function signIn({ credential }) {
        const res = await fetch(`${API_URL}/auth/google`, {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ credential }),
        });
        const body = await res.json();
        if (!res.ok) {
          // 409 且 errorCode 为 "link_required":显示密码表单,然后关联 Google。
          status.textContent = body.message;
          return;
        }
        // 把令牌保存在内存中,并把访问令牌作为 Bearer 令牌发送。
        const me = await fetch(`${API_URL}/me`, { headers: { authorization: `Bearer ${body.accessToken}` } });
        status.textContent = `Signed in as ${(await me.json()).email}`;
      }

      window.onload = () => {
        google.accounts.id.initialize({ client_id: GOOGLE_CLIENT_ID, callback: signIn });
        google.accounts.id.renderButton(document.getElementById('google-button'), { theme: 'outline', size: 'large' });
      };
    </script>
  </body>
</html>

该页面属于 Web 应用,位于其自己的来源:API 的安全响应头只允许 API 自己的脚本,而 Google 的脚本和弹窗都不属于此类。用任意静态文件服务器把它提供在 Google 客户端列出的来源上:

$ python3 -m http.server 5173 -d web

API 只接受来自 CORS_ORIGINS 的浏览器请求,因此把该来源加入 .env:

CORS_ORIGINS=http://localhost:5173

试一试

启动应用:

$ npm run start

本会话中的 ID 令牌由一个小脚本铸造,它做的事和测试一样:在本地端口上提供自己的密钥集,让 GOOGLE_JWKS_URL 指向它,并用 Google 的声明签发令牌,其中一些故意写错。使用真实客户端时,在按钮的回调中记录 credential。首次登录会创建账号,并返回 API 的令牌(这里和下文都做了缩短):

$ ADA_ID_TOKEN=eyJhbGciOiJSUzI1NiIs...
$ curl localhost:3000/auth/google --json "{\"credential\":\"$ADA_ID_TOKEN\"}"
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"0-dGAu7qrLSPwU-J...","expiresIn":900}

访问令牌与密码登录得到的令牌作用相同。该账号没有密码,也无法从中解除 Google 关联:

$ ADA="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ curl localhost:3000/notes -H "$ADA" --json '{"title":"Signed in with Google"}'
{"id":"b17693fc-a303-4e64-9367-76fa453ad921","ownerId":"8fe2d2a6-8f15-4398-8356-e6360603446d","title":"Signed in with Google","body":"","createdAt":"2026-11-23T18:50:09.352Z","updatedAt":"2026-11-23T18:50:09.352Z"}
$ curl localhost:3000/me/identities -H "$ADA"
[{"provider":"google","email":"ada@gmail.com","createdAt":"2026-11-23T18:50:09.289Z"}]
$ curl localhost:3000/auth/token --json '{"email":"ada@gmail.com","password":"correct horse battery"}'
{"message":"Invalid email or password","error":"Unauthorized","statusCode":401}
$ curl -X DELETE localhost:3000/me/identities/google -H "$ADA"
{"message":"Google is the only way to sign in to this account","error":"Conflict","statusCode":409}

Bob 用密码注册了。他第一次用同一地址进行 Google 登录时,并不会关联到他的账号。用密码登录后,他关联 Google,从那时起 Google 就能让他登录:

$ BOB_ID_TOKEN=eyJhbGciOiJSUzI1NiIs...
$ curl -i localhost:3000/auth/google --json "{\"credential\":\"$BOB_ID_TOKEN\"}"
HTTP/1.1 409 Conflict
{"message":"An account with this email exists: sign in with its password, then connect Google","error":"Conflict","statusCode":409,"errorCode":"link_required"}
$ BOB="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ curl localhost:3000/me/identities/google -H "$BOB" --json "{\"credential\":\"$BOB_ID_TOKEN\",\"password\":\"wrong\"}"
{"message":"Wrong password","error":"Forbidden","statusCode":403}
$ curl -i localhost:3000/me/identities/google -H "$BOB" --json "{\"credential\":\"$BOB_ID_TOKEN\",\"password\":\"correct horse battery\"}"
HTTP/1.1 204 No Content
$ curl localhost:3000/auth/google --json "{\"credential\":\"$BOB_ID_TOKEN\"}"
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"i0yexhWtKTqHsjxJ...","expiresIn":900}

一个签发给另一个客户端的令牌、一个伪造的令牌,以及一个地址未经 Google 验证的令牌:

$ curl localhost:3000/auth/google --json "{\"credential\":\"$OTHER_CLIENTS_ID_TOKEN\"}"
{"message":"Invalid Google ID token: unexpected audience","error":"Unauthorized","statusCode":401}
$ curl localhost:3000/auth/google --json "{\"credential\":\"$FORGED_ID_TOKEN\"}"
{"message":"Invalid Google ID token: invalid signature","error":"Unauthorized","statusCode":401}
$ curl localhost:3000/auth/google --json "{\"credential\":\"$UNVERIFIED_EMAIL_ID_TOKEN\"}"
{"message":"Google has not verified the email address of this account","error":"Forbidden","statusCode":403}

改用默认的 GOOGLE_JWKS_URL(Google 的真实密钥集)重启后,API 会拒绝替身的令牌,因为它指明的密钥 Google 没有:

$ curl localhost:3000/auth/google --json "{\"credential\":\"$ADA_ID_TOKEN\"}"
{"message":"Invalid Google ID token: no matching key","error":"Unauthorized","statusCode":401}

当密钥集无法获取时——这里是一个指向无人监听端口的 GOOGLE_JWKS_URL——回答是 503:

$ curl localhost:3000/auth/google --json "{\"credential\":\"$ADA_ID_TOKEN\"}"
{"message":"Google sign-in is unavailable","error":"Service Unavailable","statusCode":503}

API 同时记录原因:

ERROR [GoogleIdTokenVerifier] Google ID token verification failed
ERROR [GoogleIdTokenVerifier] Error: JWKS http://127.0.0.1:3359/certs is unavailable: fetch failed

测试

测试充当 Google 的替身:生成一对 RSA 密钥,从本地 HTTP 服务器把其公钥部分作为 JWKS 提供,并使用 @nestjs/authentication 的 JwtSigner 以 Google 的签发者和声明签发 ID 令牌。应用针对该密钥集运行真实的校验器;JwksClient 只在回环地址上接受纯 http。把这些设置加入测试环境,PGlite 测试也需要它们:

vitest.config.e2e.ts
// ...
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
      GOOGLE_CLIENT_IDS: 'web-client.apps.googleusercontent.com,mobile-client.apps.googleusercontent.com',
      // test/google-login.e2e-spec.ts 提供的密钥集。
      GOOGLE_JWKS_URL: 'http://127.0.0.1:3351/certs',
    },
// ...

竞争测试需要真实的 PostgreSQL 服务器和连接池,如电商教程中那样:

test/google-login.e2e-spec.ts
import { generateKeyPairSync, type KeyObject } from 'node:crypto';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
import { JwtSigner, PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { AppModule } from '../src/app.module.js';
import { identities, users } from '../src/database/schema.js';

// 真实的 PostgreSQL 加连接池,这样并发登录才会真正竞争。
const url = process.env.TEST_DATABASE_URL;

// 充当 Google:一对密钥,以及作为 JWKS 提供的公钥部分。
const google = generateKeyPairSync('rsa', { modulusLength: 2048 });
const KID = 'test-key';

/** 一个形状类似 Google 的 ID 令牌,除非 `key` 另有指定,否则用测试密钥签名。 */
function idToken(
  claims: { sub: string; email?: string; email_verified?: boolean },
  { key = google.privateKey as KeyObject, issuer = 'https://accounts.google.com', audience = 'web-client.apps.googleusercontent.com', now = Date.now } = {},
) {
  return new JwtSigner({ key, kid: KID, issuer, audience, ttl: '1h', now }).sign({ email_verified: true, ...claims });
}

describe.skipIf(!url)('Google login (e2e)', () => {
  const pool = new Pool({ connectionString: url, max: 20 });
  const db = drizzle({ client: pool });
  const jwks = createServer((_req, res) => {
    const jwk = google.publicKey.export({ format: 'jwk' });
    res.setHeader('content-type', 'application/json');
    res.end(JSON.stringify({ keys: [{ ...jwk, kid: KID, alg: 'RS256', use: 'sig' }] }));
  });
  let app: NestNodeApplication;

  beforeAll(async () => {
    await new Promise<void>((resolve) => jwks.listen(3351, '127.0.0.1', resolve));
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    await db.execute(sql`TRUNCATE users, identities, refresh_tokens CASCADE`);
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db)
      // 默认成本的 scrypt 每次哈希需要 128 MiB 和几百毫秒。
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    await app.init();
  });

  afterAll(async () => {
    await app.close(); // 同时关闭连接池
    jwks.close();
  });

  let clients = 0;
  // 每个请求使用各自的地址:登录和注册按 IP 地址限流。
  const from = () => `10.0.0.${++clients}`;

  const signInWithGoogle = (credential: string) =>
    app.inject({ method: 'POST', url: '/auth/google', payload: { credential }, remoteAddress: from() });

  /** 一次登录的访问令牌所属的用户。 */
  async function me(signIn: { json<T>(): T }) {
    const { accessToken } = signIn.json<{ accessToken: string }>();
    const res = await app.inject({ method: 'GET', url: '/me', headers: { authorization: `Bearer ${accessToken}` } });
    return res.json<{ id: string; email: string }>();
  }

  it('signs a new Google user up, then back in', async () => {
    const first = await signInWithGoogle(idToken({ sub: 'google-ada', email: 'Ada@gmail.com' }));
    expect(first.statusCode).toBe(200);
    const ada = await me(first);
    expect(ada.email).toBe('ada@gmail.com');

    // 另一个有文档记录的签发者,以及 API 的另一个客户端 ID,同样可用。
    const again = await signInWithGoogle(
      idToken({ sub: 'google-ada' }, { issuer: 'accounts.google.com', audience: 'mobile-client.apps.googleusercontent.com' }),
    );
    expect(await me(again)).toEqual(ada);
  });

  it('refuses ID tokens that are not for this API', async () => {
    const tokens = {
      'unexpected audience': idToken({ sub: 'google-eve' }, { audience: 'someone-elses.apps.googleusercontent.com' }),
      'unexpected issuer': idToken({ sub: 'google-eve' }, { issuer: 'https://accounts.example.com' }),
      'token expired': idToken({ sub: 'google-eve' }, { now: () => Date.now() - 2 * 60 * 60 * 1000 }),
      'invalid signature': idToken({ sub: 'google-eve' }, { key: generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey }),
    };
    for (const [reason, token] of Object.entries(tokens)) {
      const res = await signInWithGoogle(token);
      expect(res.json()).toMatchObject({ statusCode: 401, message: `Invalid Google ID token: ${reason}` });
    }
    const unverified = idToken({ sub: 'google-eve', email: 'mallory@example.com', email_verified: false });
    expect((await signInWithGoogle(unverified)).statusCode).toBe(403);
  });

  /** 用密码注册,并返回以新用户身份认证的请求头。 */
  async function signUp(email: string) {
    const res = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email, password: 'correct horse battery' },
      remoteAddress: from(),
    });
    return { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
  }

  it('never links a Google account to a password account by email', async () => {
    const headers = await signUp('bob@gmail.com');
    const credential = idToken({ sub: 'google-bob', email: 'bob@gmail.com' });

    const refused = await signInWithGoogle(credential);
    expect(refused.json()).toMatchObject({ statusCode: 409, errorCode: 'link_required' });

    const connect = (as: Record<string, string>, token: string, password = 'correct horse battery') =>
      app.inject({ method: 'POST', url: '/me/identities/google', headers: as, payload: { credential: token, password }, remoteAddress: from() });
    expect((await connect(headers, credential, 'a wrong guess')).statusCode).toBe(403);
    expect((await connect(headers, credential)).statusCode).toBe(204);
    expect((await connect(headers, credential)).statusCode).toBe(204); // 重试
    expect((await me(await signInWithGoogle(credential))).email).toBe('bob@gmail.com');

    // Bob 的 Google 账号是他的,而且他已经有一个了。
    const taken = await connect(await signUp('dan@gmail.com'), credential);
    expect(taken.json().message).toBe('This Google account is connected to another account');
    const second = await connect(headers, idToken({ sub: 'google-bob-2' }));
    expect(second.json().message).toBe('Disconnect your other Google account first');

    // Bob 有密码,因此 Google 可以解除一次。Ada 没有其他方式。
    const disconnect = (as: Record<string, string>) => app.inject({ method: 'DELETE', url: '/me/identities/google', headers: as });
    expect((await disconnect(headers)).statusCode).toBe(204);
    expect((await disconnect(headers)).statusCode).toBe(404);
    const ada = await signInWithGoogle(idToken({ sub: 'google-ada' }));
    const asAda = { authorization: `Bearer ${ada.json<{ accessToken: string }>().accessToken}` };
    expect((await disconnect(asAda)).statusCode).toBe(409);
  });

  it('refuses a password sign-in to an account created with Google', async () => {
    const signIn = (email: string) =>
      app.inject({ method: 'POST', url: '/auth/token', payload: { email, password: 'any password at all' }, remoteAddress: from() });
    const created = await signIn('ada@gmail.com');
    expect(created.statusCode).toBe(401);
    expect(created.json()).toEqual((await signIn('nobody@gmail.com')).json());
  });

  it('creates one user when the same Google account signs in twice at once', async () => {
    const credential = idToken({ sub: 'google-carol', email: 'carol@gmail.com' });
    // 先打开连接池的连接,否则第一个请求会在其他请求等待连接时完成。
    await Promise.all(Array.from({ length: 10 }, () => pool.query('SELECT 1')));

    const results = await Promise.all(Array.from({ length: 10 }, () => signInWithGoogle(credential)));

    expect(results.map((res) => res.statusCode)).toEqual(Array(10).fill(200));
    const ids = new Set((await Promise.all(results.map(me))).map(({ id }) => id));
    expect(ids.size).toBe(1);
    expect(await db.$count(users, eq(users.email, 'carol@gmail.com'))).toBe(1);
    expect(await db.$count(identities, eq(identities.subject, 'google-carol'))).toBe(1);
  });
});

竞争测试故意先打开连接池的连接。否则第一个请求会占用那一个已打开的连接,在其他请求连接之前就完成,于是根本不会发生竞争:即使从 signIn() 中移除第二次读取,测试也会通过。而先打开连接后,十个请求都找不到身份,移除那次读取会让其中九个返回 409。

先创建一次测试数据库,然后依次运行测试文件,因为其中两个会清空同一个数据库的表:

$ docker exec notes-db psql -U postgres -c "CREATE DATABASE notes_test"
$ TEST_DATABASE_URL=postgres://postgres:notes@localhost:5432/notes_test npm run test:e2e -- --no-file-parallelism

 Test Files  3 passed (3)
      Tests  13 passed (13)

生产环境检查清单

JWT 教程检查清单中的所有内容都适用。针对 Google 登录:

  • 在 GOOGLE_CLIENT_IDS 中只列出你自己的生产客户端 ID,并在 Google 客户端和 CORS_ORIGINS 中列出你的生产来源(带 https://)。
  • 让 API 能通过 HTTPS 访问 www.googleapis.com。 密钥会缓存 10 分钟,刷新失败时最后获取的密钥会继续服务;如果一个都没有,该路由会返回 503。
  • 在上线前加上密码重置,这样当别人用某个地址注册后,该地址的所有者能取回账号,Google 用户也能添加密码。参见重置忘记的密码。
  • 为生产环境使用独立的 Observe 密钥对,从项目的 API Keys 页面获取,作为 OBSERVE_APP_KEY 和 OBSERVE_APP_SECRET 放入平台环境:start:prod 不会加载 .env。然后关注该路由的失败:一次移动端发布向 Google 请求了某个 API 未列出的客户端 ID 的令牌,会表现为 POST /auth/google 上的 401,而 NestJS Observe 会按路由记录请求及其失败率,因此这种上升是可见的。

接下来

  • 用 nonce 阻止重放的 ID 令牌,如校验 Google ID 令牌中的提示所述。
  • 只允许你公司的 Google Workspace 账号进入:它们的令牌以 hd 携带域名,verify() 会连同其他声明一起返回。
  • 让服务端渲染的 Web 应用通过会话 Cookie 使用 Google 登录:添加「使用 Google 登录」。
  • 在注册时验证邮箱地址:验证邮箱地址。
  • 在生产环境中查看登录及其失败:可观测性。