# Google login

Source: https://docs.nestjs.com/tutorials/google-login

Add Sign in with Google to a Node.js API in TypeScript with NestJS: verify Google ID tokens, link accounts safely, and issue the API's own JWTs.

The notes API of [Build a REST API with JWT authentication](/tutorials/rest-api-jwt-authentication) signs users in with a password. This tutorial adds Google: the web or mobile app gets an **ID token** from Google's sign-in library, and the API verifies it and answers with the same access and refresh tokens as a password sign-in. Verifying is the easy part. The hard part is deciding which account a Google sign-in belongs to.

By the end, the API will:

- Verify Google ID tokens with `JwtVerifier` from [`@nestjs/authentication`](/security/authentication): the signature against Google's published keys, the issuer, the audience and the expiry.
- Create an account on a first sign-in, found again by Google's id for the account, never by its email.
- Never hand a password account to whoever signs in with Google with its address, and let its owner connect Google instead.
- Never disconnect the last way to sign in to an account.
- Prove, against PostgreSQL and a stand-in for Google, that ten concurrent first sign-ins create one account.

These are the endpoints this tutorial adds:

| Endpoint | Section |
| --- | --- |
| `POST /auth/google` | [Sign in with a Google ID token](/tutorials/google-login#sign-in-with-a-google-id-token) |
| `GET /me/identities`, `POST /me/identities/google`, `DELETE /me/identities/google` | [Connect Google to an existing account](/tutorials/google-login#connect-google-to-an-existing-account) |

#### Start from the notes API

This tutorial continues the JWT tutorial's finished application, notes included: they're what users sign in to. If you built it, keep working in that project and its database. Otherwise, create the project with the JWT tutorial's packages:

```bash
$ 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
```

Then take these from the [finished JWT tutorial](/tutorials/rest-api-jwt-authentication), as they are:

- all of `src/` (`src/notes/` included) and all of `test/`
- the `drizzle/` folder with its two migrations, `drizzle.config.ts` and `vitest.config.e2e.ts`
- the `test:e2e` script in `package.json`, and `.env` with its `DATABASE_URL` and `JWT_SECRET`, for the JWT tutorial's PostgreSQL container

Keep the migrations: this tutorial adds a third one to the same database. On a new database, apply them first. If `drizzle-kit` answers that a `snapshot.json` "is not of the latest version", the migrations were generated by an older release candidate of it: `drizzle-kit up` upgrades them.

```bash
$ npx drizzle-kit up
$ npx drizzle-kit migrate
```

#### How Google sign-in works for an API

Google's libraries sign the user in on the client: [Google Identity Services](https://developers.google.com/identity/gsi/web/guides/overview) on the web, [Credential Manager](https://developer.android.com/identity/sign-in/credential-manager-siwg) on Android, Google Sign-In on iOS. They hand it an ID token: a JWT signed by Google that names the Google account (`sub`), its email, whether Google verified it (`email_verified`), and the OAuth client it was issued to (`aud`). The client sends it to the API once, then uses the API's tokens. The API only fetches Google's public keys, and needs no client secret.

> info **Hint** A server-rendered web app that keeps users in a session cookie is better served by the authentication chapter's [redirect flow](/security/authentication#add-sign-in-with-google), where the browser goes to Google and back. It always signs in through a session, which is why this bearer-token API doesn't use it.

#### Set up a Google OAuth client

The ID tokens are issued to an OAuth client of yours, in the [Google Cloud console](https://console.cloud.google.com/):

1. In **Google Auth Platform**, fill in the **Branding** page: the app's name, a support email, your home page and privacy policy.
2. On the **Clients** page, create a client of type **Web application**.
3. Under **Authorized JavaScript origins**, add the origins of the web app that shows the button, such as `https://app.example.com`. For local development, add both `http://localhost` and `http://localhost:5173`, with your web app's port. The button calls back in JavaScript, so it needs no redirect URI.
4. Copy the client ID, which ends in `.apps.googleusercontent.com`. The API doesn't need the secret.

Mobile apps get clients of their own in the same project, as Google's guide for each platform describes. Android's Credential Manager requests tokens for the **web** client ID (`setServerClientId()`), so they name the web client as their audience. List any other client ID your apps' tokens are issued to next to the web one.

> warning **Warning** This tutorial was written and tested without a real Google sign-in. Every ID token below was signed by a stand-in for Google, with Google's claims, as in the [tests](/tutorials/google-login#test-it). The console steps follow Google's documentation at the time of writing. The verifier also ran against Google's real key set, which refused the stand-in's tokens.

The client IDs go in `.env`, comma-separated:

```bash
# Every OAuth client whose ID tokens the API accepts: the web client, then any mobile ones.
GOOGLE_CLIENT_IDS=1234567890-web.apps.googleusercontent.com
```

The configuration schema requires at least one, so a missing ID stops the application at startup. The URL of Google's keys has a default, which only the tests change:

```typescript

// ...
export const envSchema = z.object({
  // ...
  // The OAuth client IDs whose Google ID tokens the API accepts, comma-separated.
  GOOGLE_CLIENT_IDS: z
    .string()
    .transform((value) => value.split(',').map((id) => id.trim()).filter(Boolean))
    .pipe(z.array(z.string()).min(1)),
  // Google's signing keys. The tests serve their own.
  GOOGLE_JWKS_URL: z.url().default('https://www.googleapis.com/oauth2/v3/certs'),
});
// ...
```

#### Store identities, not emails

Google identifies an account by its `sub` claim, which it never reuses. An account's email can change, and an address can later belong to another Google account. So the link between a Google account and a user is a row of its own, keyed by the provider and its id for the account. A user created by Google has no password:

```typescript

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(),
  // Null for an account created by signing in with Google.
  passwordHash: text('password_hash'),
  createdAt: at('created_at').notNull().defaultNow(),
});

// The accounts at other providers that sign a user in, found by the provider's id for them.
export const identities = pgTable(
  'identities',
  {
    provider: text('provider').notNull(),
    // Google's `sub`: stable for the life of the Google account, unlike its email.
    subject: text('subject').notNull(),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    // The address the provider reported, for display only.
    email: text('email'),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [
    // One user per provider account: two first sign-ins can't create two users.
    primaryKey({ columns: [table.provider, table.subject] }),
    // One account per provider for each user.
    unique('identities_user_id_provider_key').on(table.userId, table.provider),
  ],
);

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

The primary key means PostgreSQL never lets one Google account sign in two users, whatever the code does. The unique constraint gives each user at most one Google account, so `DELETE /me/identities/google` names one link. The email in `identities` only shows the user which account is connected; nothing is looked up by it.

Generate the migration, and apply it. It makes `password_hash` nullable and creates the table; existing users keep their passwords:

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

The users repository finds a user by an identity, and creates a Google user with their identity in one transaction:

```typescript

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

  /** For password sign-in only. `passwordHash` is null for an account created with Google. */
  async findCredentials(email: string): Promise<{ user: User; passwordHash: string | null } | null> {
    // ...
  }

  /** The user that a provider's account signs in. */
  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;
  }

  /** A new user without a password, linked to a provider's account, or `null` when the email is taken. */
  createWithIdentity(email: string, provider: string, subject: string): Promise<User | null> {
    return this.db.transaction(async (tx) => {
      // A concurrent insert of the same email makes this wait for its transaction,
      // and then insert nothing if that one committed.
      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 a taken email, `ON CONFLICT DO NOTHING` returns no row and the caller decides what it means. A unique violation would abort the transaction instead, and answer 500.

A user without a password must never sign in with one. `PasswordHasher.verify()` already handles a missing hash: it checks a dummy one and answers `false`, as for an unknown email. `CredentialsService.verify()` only needs the check TypeScript now asks for:

```typescript

  async verify(email: string, password: string): Promise<User | null> {
    const found = await this.usersRepository.findCredentials(email);
    // With no account, verify() checks a dummy hash, so the response
    // time doesn't reveal which emails are registered.
    // The same goes for an account created with Google, which has no password.
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    if (!valid || !found?.passwordHash) {
      return null;
    }
    // ...
  }
```

A password sign-in to a Google account gets the same 401, in the same time, as one for an address nobody registered.

#### Verify a Google ID token

Google publishes its signing keys as a JSON Web Key Set (JWKS). `JwksClient` fetches and caches it, and refetches it when a token names a key it doesn't know (Google rotates its keys). `JwtVerifier` checks the signature against it, along with the issuer, audience and expiry. It's the verifier `JwtBearerProvider` uses for another issuer's tokens (see [Issue tokens to the mobile app](/security/authentication#issue-tokens-to-the-mobile-app)):

```typescript

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';

/** What the API takes from a verified Google ID token. */
export interface GoogleAccount {
  /** Google's id for the account: stable, never reused. */
  subject: string;
  email?: string;
  /** Whether Google verified that the account owns `email`. */
  emailVerified: boolean;
}

// Google documents both values of `iss` for its ID tokens.
const GOOGLE_ISSUERS = ['https://accounts.google.com', 'accounts.google.com'];

@Injectable()
export class GoogleIdTokenVerifier {
  private readonly logger = new Logger(GoogleIdTokenVerifier.name);
  private readonly verifiers: Map<string, JwtVerifier>;

  constructor(config: ConfigService<Env, true>) {
    // One key set, fetched and cached for both verifiers.
    const jwks = new JwksClient(config.get('GOOGLE_JWKS_URL', { infer: true }));
    const verify = (issuer: string) =>
      new JwtVerifier({
        jwks,
        issuer,
        // Tokens issued to any other client of Google's are refused.
        audience: config.get('GOOGLE_CLIENT_IDS', { infer: true }),
        required: ['exp', 'sub'],
        // Google's clock and this server's are never quite the same.
        clockTolerance: '30s',
      });
    this.verifiers = new Map(GOOGLE_ISSUERS.map((issuer) => [issuer, verify(issuer)]));
  }

  async verify(idToken: string): Promise<GoogleAccount> {
    // Picks the verifier for the issuer the token names, which that verifier then checks.
    const verifier = this.verifiers.get(unverifiedIssuer(idToken)) ?? this.verifiers.get(GOOGLE_ISSUERS[0])!;
    try {
      const claims = await 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's keys couldn't be fetched: not the client's fault, and worth retrying.
      this.logger.error('Google ID token verification failed', error);
      throw new ServiceUnavailableException('Google sign-in is unavailable');
    }
  }
}

/** The `iss` claim, read without verifying anything. */
function unverifiedIssuer(token: string): string {
  try {
    const payload = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString());
    return typeof payload?.iss === 'string' ? payload.iss : '';
  } catch {
    return '';
  }
}
```

- **The audience is your client IDs.** Google signs every application's ID tokens with the same keys. Without the check, a token a user's browser gave another site would sign them in here, which is why `JwtVerifier` refuses a `jwks` without an `audience`.
- **Two issuers, two verifiers.** Google documents both `https://accounts.google.com` and `accounts.google.com` as an ID token's `iss`, and the `issuer` option takes one value. The verifiers share one `JwksClient`, so the keys are fetched once. Reading `iss` unverified is safe: it only picks the verifier that then checks it.
- **A bad token is a 401, an outage a 503.** A `JwtError` says why a token failed. When Google's keys can't be fetched, the client should retry later, not sign the user out.

> info **Hint** An ID token is valid for about an hour, and whoever copies one can exchange it here until then. Google's libraries put a `nonce` of yours in the token (the `nonce` option of the web `initialize()` call, `setNonce()` on Android). An API that issues a random nonce per sign-in and accepts each once stops replays; `verify()` returns every claim, so the check is a comparison of `claims.nonce`. It needs an endpoint and a table of its own, so this tutorial leaves it out.

#### Sign in with a Google ID token

A verified token leads to one of three cases: the Google account is linked to a user already, it isn't and its address is free, or it isn't and the address belongs to an account:

```typescript

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) {}

  /** The user a Google account signs in, created on its first sign-in. */
  async signIn(google: GoogleAccount): Promise<User> {
    const linked = await this.usersRepository.findByIdentity('google', google.subject);
    if (linked) {
      return linked;
    }
    // A first sign-in. The email becomes the account's, so it must be one Google verified.
    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;
    }
    // The email is taken. A concurrent first sign-in with this Google account may have
    // just taken it, and then that user is this one.
    const raced = await this.usersRepository.findByIdentity('google', google.subject);
    if (raced) {
      return raced;
    }
    // Someone signed up with this email and a password. Linking now would let them in too.
    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',
    });
  }
}
```

A returning Google account signs in to its user whatever its email says now. A first sign-in creates a user only with an address Google verified; an unverified one could be someone else's, so it gets a 403.

##### Prevent account pre-hijacking

Linking by address hands accounts to attackers here, because the JWT tutorial never checks that users own the address they sign up with. Someone signs up first with `ada@gmail.com` and a password of their choosing. When Ada later signs in with Google, she'd land in that account, keep her notes in it, and the attacker would still have the password. This is account pre-hijacking.

So that sign-in gets a 409 with `errorCode` set to `link_required`: the client asks the user to sign in with their password, then connect Google. The answer reveals that the address has an account, but only to someone Google verified it for. If the owner never set that password, someone else did, and a [password reset](/security/authentication#reset-forgotten-passwords) gives them the account back. An API that [verifies email addresses](/security/authentication#verify-email-addresses) can link accounts whose address both sides verified, as the authentication chapter does.

##### Two first sign-ins at once

A double-click sends two first sign-ins for one Google account. Both find no identity and insert a user with the same email; PostgreSQL makes the second insert wait for the first transaction, then insert nothing. The second request reads the identity again and signs in to the user the first one created. Without that read, it would answer 409, as if a stranger owned the address.

##### The route

The request body carries the ID token as `credential`, the name Google's web library uses:

```typescript

// ...
// What Google's sign-in libraries hand the client: a signed JWT, a little over 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>;
```

The controller verifies the token, finds the user, and issues tokens with `TokenService`, as `POST /auth/token` does:

```typescript

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,
  ) {}

  // The same tokens as POST /auth/token, for a Google ID token.
  @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' });
  }
}
```

The tokens are the API's own, so the notes routes and `POST /auth/token/refresh` don't care how the user signed in. The route has its own rate limit, because the `account` limit counts per email in the request body, and this body has none. An ID token is a credential, so add `credential` to the logger's `redact` list in `main.ts`:

```typescript

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

The module registrations follow in the next section.

#### Connect Google to an existing account

A signed-in user connects Google from their account page: the web app shows the same button, and sends the ID token to `POST /me/identities/google`. No email match is needed, since the access token proves the account and the ID token the Google account. The password is: connecting adds a lasting way in, and an access token stolen for its 15 minutes must not be enough to add the thief's Google account. The repository lists, links and unlinks:

```typescript

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 };

/** The provider accounts connected to a user. */
@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));
  }

  /** Whose the provider account is: the user it is linked to, or `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;
  }

  /** Whether the link was made: not when the provider account, or the user's account at the provider, is linked already. */
  async link(userId: string, provider: string, subject: string, email?: string): Promise<boolean> {
    // The constraints decide, so of two concurrent links of one account, one succeeds.
    const linked = await this.db
      .insert(identities)
      .values({ userId, provider, subject, email })
      .onConflictDoNothing()
      .returning({ provider: identities.provider });
    return linked.length > 0;
  }

  /** Whether the link was removed. Never the user's last way to sign in: a user without a password keeps it. */
  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)));
    // One statement: the check and the delete can't be separated by another request.
    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` provides it, and exports it with `UsersRepository`:

```typescript

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 {}
```

The service checks the password, and turns what the statements changed into answers:

```typescript

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,
  ) {}

  /** Links a Google account to a signed-in user who confirmed their password. */
  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;
    }
    // Not linked: the Google account is this user's already (a retry), someone else's,
    // or this user has another one.
    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');
  }
}
```

- **The insert decides.** Two users connecting the same Google account at once would both pass a check that reads first; the primary key lets one insert through. The read after a refused insert only picks the answer.
- **A wrong password is a 403.** A 401 would tell the client its access token is bad, and to sign the user out.
- **The last way to sign in stays.** Disconnecting Google from a user with no password would lock them out of their notes. The condition is part of the `DELETE`, so nothing can change in between, and such a user gets a 409.

The controller is behind the global authentication guard, like `GET /me`:

```typescript

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);
  }

  // It checks a password, so it's limited like sign-in.
  @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);
  }
}
```

Register both controllers and the new providers in `AuthModule`:

```typescript

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 {}
```

#### Add the Sign in with Google button

On the web, Google Identity Services renders the button, signs the user in, and calls your function with the ID token. A minimal page of the web app posts it to the API:

```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 calls this with the ID token, as `credential`, once the user picks an account.
      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 with errorCode "link_required": show the password form, then connect Google.
          status.textContent = body.message;
          return;
        }
        // Keep the tokens in memory, and send the access token as a bearer token.
        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>
```

The page belongs to the web app, on its own origin: the API's [security headers](/tutorials/rest-api-jwt-authentication#set-security-headers-and-cors) allow only the API's own scripts, and Google's script and popup are neither. Serve it on an origin the Google client lists, with any static file server:

```bash
$ python3 -m http.server 5173 -d web
```

The API accepts browser requests only from `CORS_ORIGINS`, so add that origin to `.env`:

```bash
CORS_ORIGINS=http://localhost:5173
```

#### Try it

Start the application:

```bash
$ npm run start
```

The ID tokens in this session were minted by a small script that does what the tests do: it served its key set on a local port, which `GOOGLE_JWKS_URL` pointed at, and signed tokens with Google's claims, some of them wrong on purpose. With a real client, log `credential` in the button's callback. A first sign-in creates the account and answers with the API's tokens (shortened here and below):

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

The access token works like a password sign-in's. The account has no password, and Google can't be disconnected from it:

```bash
$ 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 signed up with a password. His first Google sign-in, with the same address, isn't linked to his account. Once signed in with his password, he connects Google, and from then on it signs him in:

```bash
$ 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}
```

A token issued to another client, a forged one, and one with an address Google didn't verify:

```bash
$ 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}
```

Restarted with the default `GOOGLE_JWKS_URL`, Google's real key set, the API refuses the stand-in's token, which names a key Google doesn't have:

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

With a key set that can't be fetched, here a `GOOGLE_JWKS_URL` on a port where nothing listens, the answer is a 503:

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

The API logs the reason at the same time:

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

#### Test it

The tests stand in for Google: they generate an RSA key pair, serve its public half as a JWKS from a local HTTP server, and sign ID tokens with Google's issuer and claims using `JwtSigner` from `@nestjs/authentication`. The application runs its real verifier against that key set; `JwksClient` accepts plain `http` only on loopback addresses. Add the settings to the test environment, which the PGlite tests need too:

```typescript

// ...
    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',
      // The key set test/google-login.e2e-spec.ts serves.
      GOOGLE_JWKS_URL: 'http://127.0.0.1:3351/certs',
    },
// ...
```

The race needs a real PostgreSQL server and a pool, as in the [e-commerce tutorial](/tutorials/ecommerce-backend#test-it):

```typescript

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';

// A real PostgreSQL with a pool, so concurrent sign-ins really race.
const url = process.env.TEST_DATABASE_URL;

// Stands in for Google: a key pair, and its public half served as a JWKS.
const google = generateKeyPairSync('rsa', { modulusLength: 2048 });
const KID = 'test-key';

/** An ID token shaped like Google's, signed with the test key unless `key` says otherwise. */
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 at the default cost takes 128 MiB and a few hundred ms per hash.
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    await app.init();
  });

  afterAll(async () => {
    await app.close(); // closes the pool too
    jwks.close();
  });

  let clients = 0;
  // Each request from an address of its own: sign-in and sign-up are rate-limited per IP address.
  const from = () => `10.0.0.${++clients}`;

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

  /** The user that a sign-in's access token belongs to. */
  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');

    // The other documented issuer, and another of the API's client IDs, work too.
    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);
  });

  /** Signs up with a password, and returns the headers that authenticate as the new user. */
  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); // a retry
    expect((await me(await signInWithGoogle(credential))).email).toBe('bob@gmail.com');

    // Bob's Google account is his, and he has one already.
    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 has a password, so Google can go, once. Ada has nothing else.
    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' });
    // Opens the pool's connections first, or the first request finishes while the others wait for theirs.
    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);
  });
});
```

The race test opens the pool's connections first on purpose. Without that, the first request takes the one open connection and finishes before the others have connected, so nothing races: the test passed with the second read removed from `signIn()`. With it, all ten find no identity, and removing that read makes nine of them answer 409.

Create a test database once, then run the test files one after the other, since two of them truncate tables of the same database:

```bash
$ 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)
```

#### Production checklist

Everything in the JWT tutorial's [checklist](/tutorials/rest-api-jwt-authentication#production-checklist) applies. For Google sign-in:

- **List only your own production client IDs** in `GOOGLE_CLIENT_IDS`, and your production origins, with `https://`, in the Google client and in `CORS_ORIGINS`.
- **Let the API reach `www.googleapis.com` over HTTPS.** Keys are cached for 10 minutes, and the last ones fetched keep serving when a refresh fails; with none at all, the route answers 503.
- **Add password resets before launch**, so the owner of an address someone else signed up with can take the account back, and a Google user can add a password. See [Reset forgotten passwords](/security/authentication#reset-forgotten-passwords).
- **Watch the route's failures.** A mobile release that asks Google for tokens for a client ID the API doesn't list shows up as 401s on `POST /auth/google`. [NestJS Observe](/observability/overview) records requests per route with their failure rate, so the rise is visible.

#### What's next

- Stop replayed ID tokens with a nonce, as the hint in [Verify a Google ID token](/tutorials/google-login#verify-a-google-id-token) describes.
- Let in only your company's Google Workspace accounts: their tokens carry the domain as `hd`, which `verify()` returns with the other claims.
- Sign a server-rendered web app in with Google, through a session cookie: [Add "Sign in with Google"](/security/authentication#add-sign-in-with-google).
- Verify email addresses at sign-up: [Verify email addresses](/security/authentication#verify-email-addresses).
- See sign-ins and their failures in production: [Observability](/observability/overview).
