Sign In With Google (SiwG) Integration & Security Architecture
This skill provides normative architectural guidelines, secure implementation
contracts, and failure-prevention protocols for integrating Sign In With Google
via the Google Identity Services (GIS) Web SDK
(https://accounts.google.com/gsi/client).
1. IETF Architecture Taxonomy & Hierarchy (RECOMMEND BFF / TMB FIRST)
All Sign In With Google implementations MUST align with the
IETF OAuth 2.0 for Browser-Based Applications (draft-ietf-oauth-browser-based-apps)
taxonomy.
[!IMPORTANT] Primary Recommendation: Always recommend backend-mediated
patterns (Pattern A: Backend For Frontend or Pattern B: Token-Mediating
Backend / Redirect Mode) as the most secure, robust, and industry-standard
architectures whenever an application has a backend server. Fall back to
client-only browser patterns (Patterns C & D) only when constrained by
serverless static hosting or offline-first PWA requirements.
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ IETF ARCHITECTURE HIERARCHY & SELECTION │
├──────────────────────────┬──────────────────────────┬───────────────────────────────────┤
│ Pattern A (RECOMMENDED): │ Pattern B (RECOMMENDED): │ Patterns C & D (Fallbacks): │
│ Backend For Frontend │ Token-Mediating Backend │ Browser-Based OAuth Client │
│ (BFF - IETF § 6.1) │ (TMB / Redirect § 6.2) │ (JavaScript-Only - IETF § 6.3) │
├──────────────────────────┼──────────────────────────┼───────────────────────────────────┤
│ 🏆 GOLD STANDARD │ 🚀 NATIVE FORM REDIRECT │ ⚡ STATIC SPA / 💾 OFFLINE PWA │
│ • Full-stack SPA + API │ • Server-rendered & apps │ • Pure client-side or offline PWAs│
│ • Client JS fetch to API │ • GIS HTTP POST login_uri│ • C: Ephemeral in-memory closure │
│ • HttpOnly session cookie│ • Direct server redirect │ • D: WebCrypto Encrypted IndexedDB│
│ • Tokens never in browser│ • Tokens never in JS │ • Strict WebCrypto nonces / keys │
└──────────────────────────┴──────────────────────────┴───────────────────────────────────┘
🏆 Pattern A: Backend For Frontend (BFF - IETF § 6.1) — STRONGLY RECOMMENDED
Why it is the Gold Standard: ID tokens (JWTs) and access tokens are
never exposed to browser JavaScript across page reloads. This provides
complete architectural immunity against XSS token harvesting.
Architecture: The browser frontend loads the GIS SDK, captures the
credential in JavaScript callback (callback: handleCredentialResponse),
and immediately forwards the ID token (JWT) via fetch('/api/auth/google', { method: 'POST' }) to the backend.
Backend Responsibilities: The backend validates the JWT cryptographic
signature against Google's public JWKs
(google.oauth2.id_token.verify_oauth2_token), checks the aud, hd, and
nonce claims against server session state, creates a server session, and
issues a first-party HttpOnly; Secure; SameSite=Lax session cookie.
See full implementation in
references/bff_fastapi_verification.md.
🚀 Pattern B: Token-Mediating Backend via login_uri Redirect (IETF § 6.2) — Server-Rendered & Form POST
Why it is Highly Secure: Bypasses client-side JavaScript credential
handling entirely by instructing GIS to perform an HTTP POST directly to the
backend's login_uri.
Architecture: Configured via google.accounts.id.initialize({ client_id, login_uri: "https://example.com/api/auth/callback", ux_mode: "redirect" })
or HTML attributes (data-login_uri="https://example.com/api/auth/callback"
and data-ux_mode="redirect").
Backend Responsibilities: The backend receives the ID token as a form
POST body (credential parameter), validates the double-submit
g_csrf_token cookie against the g_csrf_token POST body field,
cryptographically verifies the ID token server-side, establishes a session
cookie, and returns a standard HTTP 302/303 redirect.
See full implementation in
references/tmb_login_uri_redirect.md.
Pattern C: Browser-Based OAuth Client — Ephemeral In-Memory (IETF § 6.3) — Fallback for Static SPAs
Scope: Use ONLY when deployment is strictly serverless/static (e.g.,
GitHub Pages, Firebase static hosting) with no backend component.
Storage Invariant: The ID token is held strictly in private JavaScript
memory/closures during the active tab session. Never store raw tokens in
localStorage or sessionStorage.
Session Renewal: Uses GIS One Tap / FedCM auto-select (auto_select: true) to transparently re-acquire fresh ID tokens into memory on page
reload without persistent browser storage.
XSS & Replay Protection: Generate a cryptographic nonce via
window.crypto.getRandomValues() and pass it directly to
google.accounts.id.initialize({ client_id, nonce: clientNonce }). Validate
that payload.nonce === clientNonce before trusting claims in memory.
See full implementation in
references/in_memory_spa_nonce.md.
Pattern D: Browser-Based OAuth Client — WebCrypto Encrypted IndexedDB (IETF § 6.3) — Fallback for Offline PWAs
Scope: Use ONLY for offline-first Progressive Web Apps (PWAs) where user
authentication proof must survive tab refreshes when disconnected from the
network.
Storage Invariant: NEVER store raw plaintext ID tokens in
localStorage. Encrypt the ID token payload using WebCrypto AES-GCM
with a non-extractable session key (extractable: false) before writing
ciphertext and IV to IndexedDB.
See full implementation in
references/offline_pwa_encryption.md.
2. Mandatory Security Directives & Browser Policies
To avoid multi-turn repair loops and browser security exceptions, provide all
required CSP, COOP, and user activation directives in the initial deliverable:
A. Content Security Policy (CSP) Directives
Content-Security-Policy:
script-src 'self' https://accounts.google.com/gsi/client;
frame-src https://accounts.google.com/gsi/;
connect-src https://accounts.google.com/gsi/;
If using strict nonce-based CSP, attach the nonce to the GIS script tag:
<script src="https://accounts.google.com/gsi/client" async defer nonce="{{NONCE}}"></script>.
B. Cross-Origin Opener Policy (COOP)
To allow GIS popup dialogs to communicate credentials back to the parent window
via postMessage:
Cross-Origin-Opener-Policy: same-origin-allow-popups
(Serving same-origin without allow-popups breaks GIS popups and results in
silent failures).
C. Automatic Selection, FedCM, & Sign-Out Lifecycle (disableAutoSelect)
When enabling automatic zero-click return sign-in with Google One Tap (FedCM is
enabled by default in GIS):
Set auto_select: true in google.accounts.id.initialize({...}) (do not
pass the deprecated use_fedcm_for_prompt parameter).
Deprecated Library Warning: NEVER mix deprecated gapi.auth2
(gapi.auth2.init, gapi.auth2.getAuthInstance().signOut()) with Google
Identity Services (GIS). gapi.auth2 is completely retired; use GIS methods
exclusively.
Sign-Out Protocol: When the user explicitly logs out of your
application, you MUST call google.accounts.id.disableAutoSelect():
function handleUserLogout() {
// 1. Disable automatic One Tap / FedCM re-authentication
google.accounts.id.disableAutoSelect();
// 2. Clear application session state / server cookie
fetch('/api/auth/logout', { method: 'POST' }).then(() => {
window.location.href = '/login';
});
}
(Failing to call disableAutoSelect() causes an immediate automatic
re-login loop on the next page visit after intentional user logout).
D. Reliable Dynamic Script Loading & Framework Lifecycle (React, Next.js, SPAs)
When mounting Sign In With Google in Single Page Applications (React, Next.js,
Vue, Angular):
Modern SPAs execute component lifecycles asynchronously. Attempting to
access window.google.accounts.id before <script src="https://accounts.google.com/gsi/client"> has finished loading causes
ReferenceError: google is not defined.
NEVER use gapi or polling (setInterval): Use deterministic dynamic
script loading with onload / addEventListener('load') event listeners.
Dynamic Script Loader Pattern:
import React, { useEffect, useState } from 'react';
export function useGoogleIdentityScript() {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
if (window.google?.accounts?.id) {
setIsLoaded(true);
return;
}
const existingScript = document.querySelector(
'script[src="https://accounts.google.com/gsi/client"]'
);
if (existingScript) {
existingScript.addEventListener('load', () => setIsLoaded(true));
return;
}
const script = document.createElement('script');
script.src = 'https://accounts.google.com/gsi/client';
script.async = true;
script.defer = true;
script.onload = () => setIsLoaded(true);
document.head.appendChild(script);
}, []);
return isLoaded;
}
(Always use deterministic onload event listeners or framework <Script strategy="afterInteractive"> rather than brittle setInterval polling).
E. Embedded Iframes & Permissions Policy (identity-credentials-get)
When embedding Sign In With Google or One Tap inside cross-origin <iframe>
elements or widget integrations, modern browser security models and FedCM
require explicit Permissions Policy delegation on the container frame:
<iframe
src="https://example.com/embed"
allow="identity-credentials-get 'src' https://accounts.google.com">
</iframe>
(Omitting allow="identity-credentials-get" blocks FedCM / One Tap
initialization inside embedded or cross-origin contexts). See full integration
guide in references/intermediate_iframe.md.
3. Implementation Contracts & Anti-Pattern Bans
A. Strict Ban on Legacy GAPI (gapi.auth2)
NEVER import or reference gapi.auth2, gapi.auth2.init,
gapi.auth2.getAuthInstance(), or gapi.signin2. Always warn that
gapi.auth2 is deprecated and decommissioned.
GIS (google.accounts.id.* and google.accounts.oauth2.*) is completely
stateless. It replaces all legacy GAPI authentication libraries.
4. Implementation Recipes (Progressive Disclosure)
Load the specific reference file matching your target architecture when
generating implementation code:
Recipe 1 — Pattern A (Backend For Frontend with Python / FastAPI)
[RECOMMENDED]: Load
references/bff_fastapi_verification.md
for custom UI button prompting, google.oauth2.id_token.verify_oauth2_token
cryptographic verification, nonce replay checks, Google Workspace hd
domain enforcement, and HttpOnly; Secure; SameSite=Lax session cookie
issuance.
Recipe 2 — Pattern B (Token-Mediating Backend with login_uri Form POST
Redirect) [RECOMMENDED]: Load
references/tmb_login_uri_redirect.md
for data-login_uri / ux_mode: 'redirect' frontend setup and FastAPI
double-submit g_csrf_token cookie vs. form-body validation.
Recipe 3 — Pattern C (Browser-Based Ephemeral In-Memory SPA with Native
GIS Nonce) [Fallback]: Load
references/in_memory_spa_nonce.md for
WebCrypto nonce generation (google.accounts.id.initialize({ client_id, nonce: clientNonce })), UTF-8 safe Base64URL JWT decoding, and private
closure token management.
Recipe 4 — Pattern D (Browser-Based WebCrypto Encrypted IndexedDB for
Offline PWAs) [Fallback]: Load
references/offline_pwa_encryption.md
for non-extractable (extractable: false) AES-GCM CryptoKey generation
and encrypted IndexedDB storage.
Recipe 5 — Embedded Cross-Origin Contexts (gsi/intermediate): Load
references/intermediate_iframe.md for
<div id="g_id_intermediate_iframe">, allow="identity-credentials-get",
and strict window.postMessage origin verification.
5. Sign-Out & Account Revocation Across All Patterns
export function handleSignOut(userEmail) {
// 1. Disable client-side One Tap auto-selection
google.accounts.id.disableAutoSelect();
// 2. Revoke OAuth grant if user disconnected account
if (userEmail) {
google.accounts.id.revoke(userEmail, () => {
console.log('User grant revoked');
});
}
// 3. Clear storage / session
AuthManager.clear(); // Pattern C
fetch('/api/auth/logout', { method: 'POST' }); // Pattern A
}
6. References & Normative Standards
1---2name: sign-in-with-google-web3metadata:4 source: https://skillmd.com/skills/google/sign-in-with-google-web5 category: Identity6 version: "1.0.0"7description: >-8 Implement, configure, and secure Sign In With Google (SiwG) using Google Identity9 Services (GIS / `https://accounts.google.com/gsi/client`) across web architectures.10 Use when creating Google sign-in buttons, implementing Google One Tap with FedCM,11 integrating GIS in React/Next.js/Angular/HTML, verifying ID tokens on backend12 runtimes (Python/Node.js/Go/Java), enforcing Google Workspace domain restrictions13 (`hd`), securing client-side ID tokens via WebCrypto nonces or encrypted IndexedDB,14 embedding in cross-origin iframes via the Intermediate Iframe API15 (`https://accounts.google.com/gsi/intermediate`), configuring Content Security16 Policy (CSP), COOP, and Permissions Policy (`identity-credentials-get`) headers,17 or handling sign-out and revocation. Don't use for legacy Google Sign-In (`gapi.auth2`),18 Google Cloud IAM service accounts, or Android/iOS native Credential Manager.19---2021# Sign In With Google (SiwG) Integration & Security Architecture2223This skill provides normative architectural guidelines, secure implementation24contracts, and failure-prevention protocols for integrating Sign In With Google25via the Google Identity Services (GIS) Web SDK26(`https://accounts.google.com/gsi/client`).2728## 1. IETF Architecture Taxonomy & Hierarchy (RECOMMEND BFF / TMB FIRST)2930All Sign In With Google implementations MUST align with the31[IETF OAuth 2.0 for Browser-Based Applications (`draft-ietf-oauth-browser-based-apps`)](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps#name-application-architecture-pa)32taxonomy.3334> [!IMPORTANT] **Primary Recommendation:** Always recommend backend-mediated35> patterns (**Pattern A: Backend For Frontend** or **Pattern B: Token-Mediating36> Backend / Redirect Mode**) as the most secure, robust, and industry-standard37> architectures whenever an application has a backend server. Fall back to38> client-only browser patterns (Patterns C & D) only when constrained by39> serverless static hosting or offline-first PWA requirements.4041<!-- mdformat off(reason: preserve ASCII architecture diagram width) -->42```43┌─────────────────────────────────────────────────────────────────────────────────────────┐44│ IETF ARCHITECTURE HIERARCHY & SELECTION │45├──────────────────────────┬──────────────────────────┬───────────────────────────────────┤46│ Pattern A (RECOMMENDED): │ Pattern B (RECOMMENDED): │ Patterns C & D (Fallbacks): │47│ Backend For Frontend │ Token-Mediating Backend │ Browser-Based OAuth Client │48│ (BFF - IETF § 6.1) │ (TMB / Redirect § 6.2) │ (JavaScript-Only - IETF § 6.3) │49├──────────────────────────┼──────────────────────────┼───────────────────────────────────┤50│ 🏆 GOLD STANDARD │ 🚀 NATIVE FORM REDIRECT │ ⚡ STATIC SPA / 💾 OFFLINE PWA │51│ • Full-stack SPA + API │ • Server-rendered & apps │ • Pure client-side or offline PWAs│52│ • Client JS fetch to API │ • GIS HTTP POST login_uri│ • C: Ephemeral in-memory closure │53│ • HttpOnly session cookie│ • Direct server redirect │ • D: WebCrypto Encrypted IndexedDB│54│ • Tokens never in browser│ • Tokens never in JS │ • Strict WebCrypto nonces / keys │55└──────────────────────────┴──────────────────────────┴───────────────────────────────────┘56```57<!-- mdformat on -->5859### 🏆 Pattern A: Backend For Frontend (BFF - IETF § 6.1) — STRONGLY RECOMMENDED6061* **Why it is the Gold Standard**: ID tokens (JWTs) and access tokens are62 never exposed to browser JavaScript across page reloads. This provides63 complete architectural immunity against XSS token harvesting.6465* **Architecture**: The browser frontend loads the GIS SDK, captures the66 credential in JavaScript callback (`callback: handleCredentialResponse`),67 and immediately forwards the ID token (JWT) via `fetch('/api/auth/google', {68 method: 'POST' })` to the backend.6970* **Backend Responsibilities**: The backend validates the JWT cryptographic71 signature against Google's public JWKs72 (`google.oauth2.id_token.verify_oauth2_token`), checks the `aud`, `hd`, and73 `nonce` claims against server session state, creates a server session, and74 issues a first-party `HttpOnly; Secure; SameSite=Lax` session cookie.7576* See full implementation in77 [references/bff_fastapi_verification.md](references/bff_fastapi_verification.md).7879### 🚀 Pattern B: Token-Mediating Backend via `login_uri` Redirect (IETF § 6.2) — Server-Rendered & Form POST8081* **Why it is Highly Secure**: Bypasses client-side JavaScript credential82 handling entirely by instructing GIS to perform an HTTP POST directly to the83 backend's `login_uri`.8485* **Architecture**: Configured via `google.accounts.id.initialize({ client_id,86 login_uri: "https://example.com/api/auth/callback", ux_mode: "redirect" })`87 or HTML attributes (`data-login_uri="https://example.com/api/auth/callback"`88 and `data-ux_mode="redirect"`).8990* **Backend Responsibilities**: The backend receives the ID token as a form91 POST body (`credential` parameter), validates the double-submit92 `g_csrf_token` cookie against the `g_csrf_token` POST body field,93 cryptographically verifies the ID token server-side, establishes a session94 cookie, and returns a standard HTTP 302/303 redirect.9596* See full implementation in97 [references/tmb_login_uri_redirect.md](references/tmb_login_uri_redirect.md).9899### Pattern C: Browser-Based OAuth Client — Ephemeral In-Memory (IETF § 6.3) — Fallback for Static SPAs100101* **Scope**: Use ONLY when deployment is strictly serverless/static (e.g.,102 GitHub Pages, Firebase static hosting) with no backend component.103104* **Storage Invariant**: The ID token is held strictly in private JavaScript105 memory/closures during the active tab session. **Never store raw tokens in106 `localStorage` or `sessionStorage`**.107108* **Session Renewal**: Uses GIS One Tap / FedCM auto-select (`auto_select:109 true`) to transparently re-acquire fresh ID tokens into memory on page110 reload without persistent browser storage.111112* **XSS & Replay Protection**: Generate a cryptographic `nonce` via113 `window.crypto.getRandomValues()` and pass it directly to114 `google.accounts.id.initialize({ client_id, nonce: clientNonce })`. Validate115 that `payload.nonce === clientNonce` before trusting claims in memory.116117* See full implementation in118 [references/in_memory_spa_nonce.md](references/in_memory_spa_nonce.md).119120### Pattern D: Browser-Based OAuth Client — WebCrypto Encrypted IndexedDB (IETF § 6.3) — Fallback for Offline PWAs121122* **Scope**: Use ONLY for offline-first Progressive Web Apps (PWAs) where user123 authentication proof must survive tab refreshes when disconnected from the124 network.125126* **Storage Invariant**: **NEVER store raw plaintext ID tokens in127 `localStorage`**. Encrypt the ID token payload using WebCrypto `AES-GCM`128 with a non-extractable session key (`extractable: false`) before writing129 ciphertext and IV to `IndexedDB`.130131* See full implementation in132 [references/offline_pwa_encryption.md](references/offline_pwa_encryption.md).133134--------------------------------------------------------------------------------135136## 2. Mandatory Security Directives & Browser Policies137138To avoid multi-turn repair loops and browser security exceptions, provide all139required CSP, COOP, and user activation directives in the initial deliverable:140141### A. Content Security Policy (CSP) Directives142143```http144Content-Security-Policy:145 script-src 'self' https://accounts.google.com/gsi/client;146 frame-src https://accounts.google.com/gsi/;147 connect-src https://accounts.google.com/gsi/;148```149150If using strict nonce-based CSP, attach the nonce to the GIS script tag:151`<script src="https://accounts.google.com/gsi/client" async defer152nonce="{{NONCE}}"></script>`.153154### B. Cross-Origin Opener Policy (COOP)155156To allow GIS popup dialogs to communicate credentials back to the parent window157via `postMessage`:158159```http160Cross-Origin-Opener-Policy: same-origin-allow-popups161```162163*(Serving `same-origin` without `allow-popups` breaks GIS popups and results in164silent failures).*165166### C. Automatic Selection, FedCM, & Sign-Out Lifecycle (`disableAutoSelect`)167168When enabling automatic zero-click return sign-in with Google One Tap (FedCM is169enabled by default in GIS):170171* Set `auto_select: true` in `google.accounts.id.initialize({...})` (do not172 pass the deprecated `use_fedcm_for_prompt` parameter).173174* **Deprecated Library Warning**: NEVER mix deprecated `gapi.auth2`175 (`gapi.auth2.init`, `gapi.auth2.getAuthInstance().signOut()`) with Google176 Identity Services (GIS). `gapi.auth2` is completely retired; use GIS methods177 exclusively.178179* **Sign-Out Protocol**: When the user explicitly logs out of your180 application, you **MUST** call `google.accounts.id.disableAutoSelect()`:181182 ```javascript183 function handleUserLogout() {184 // 1. Disable automatic One Tap / FedCM re-authentication185 google.accounts.id.disableAutoSelect();186187 // 2. Clear application session state / server cookie188 fetch('/api/auth/logout', { method: 'POST' }).then(() => {189 window.location.href = '/login';190 });191 }192 ```193194* *(Failing to call `disableAutoSelect()` causes an immediate automatic195 re-login loop on the next page visit after intentional user logout).*196197### D. Reliable Dynamic Script Loading & Framework Lifecycle (React, Next.js, SPAs)198199When mounting Sign In With Google in Single Page Applications (React, Next.js,200Vue, Angular):201202* Modern SPAs execute component lifecycles asynchronously. Attempting to203 access `window.google.accounts.id` before `<script204 src="https://accounts.google.com/gsi/client">` has finished loading causes205 `ReferenceError: google is not defined`.206207* **NEVER use `gapi` or polling (`setInterval`)**: Use deterministic dynamic208 script loading with `onload` / `addEventListener('load')` event listeners.209210* **Dynamic Script Loader Pattern**:211212 ```tsx213 import React, { useEffect, useState } from 'react';214215 export function useGoogleIdentityScript() {216 const [isLoaded, setIsLoaded] = useState(false);217218 useEffect(() => {219 if (window.google?.accounts?.id) {220 setIsLoaded(true);221 return;222 }223224 const existingScript = document.querySelector(225 'script[src="https://accounts.google.com/gsi/client"]'226 );227 if (existingScript) {228 existingScript.addEventListener('load', () => setIsLoaded(true));229 return;230 }231232 const script = document.createElement('script');233 script.src = 'https://accounts.google.com/gsi/client';234 script.async = true;235 script.defer = true;236 script.onload = () => setIsLoaded(true);237 document.head.appendChild(script);238 }, []);239240 return isLoaded;241 }242 ```243244* *(Always use deterministic `onload` event listeners or framework `<Script245 strategy="afterInteractive">` rather than brittle `setInterval` polling).*246247### E. Embedded Iframes & Permissions Policy (`identity-credentials-get`)248249When embedding Sign In With Google or One Tap inside cross-origin `<iframe>`250elements or widget integrations, modern browser security models and FedCM251require explicit Permissions Policy delegation on the container frame:252253```html254<iframe255 src="https://example.com/embed"256 allow="identity-credentials-get 'src' https://accounts.google.com">257</iframe>258```259260*(Omitting `allow="identity-credentials-get"` blocks FedCM / One Tap261initialization inside embedded or cross-origin contexts).* See full integration262guide in [references/intermediate_iframe.md](references/intermediate_iframe.md).263264--------------------------------------------------------------------------------265266## 3. Implementation Contracts & Anti-Pattern Bans267268### A. Strict Ban on Legacy GAPI (`gapi.auth2`)269270* **NEVER** import or reference `gapi.auth2`, `gapi.auth2.init`,271 `gapi.auth2.getAuthInstance()`, or `gapi.signin2`. Always warn that272 `gapi.auth2` is deprecated and decommissioned.273274* GIS (`google.accounts.id.*` and `google.accounts.oauth2.*`) is completely275 stateless. It replaces all legacy GAPI authentication libraries.276277--------------------------------------------------------------------------------278279## 4. Implementation Recipes (Progressive Disclosure)280281Load the specific reference file matching your target architecture when282generating implementation code:283284* **Recipe 1 — Pattern A (Backend For Frontend with Python / FastAPI)285 [RECOMMENDED]**: Load286 [references/bff_fastapi_verification.md](references/bff_fastapi_verification.md)287 for custom UI button prompting, `google.oauth2.id_token.verify_oauth2_token`288 cryptographic verification, `nonce` replay checks, Google Workspace `hd`289 domain enforcement, and `HttpOnly; Secure; SameSite=Lax` session cookie290 issuance.291292* **Recipe 2 — Pattern B (Token-Mediating Backend with `login_uri` Form POST293 Redirect) [RECOMMENDED]**: Load294 [references/tmb_login_uri_redirect.md](references/tmb_login_uri_redirect.md)295 for `data-login_uri` / `ux_mode: 'redirect'` frontend setup and FastAPI296 double-submit `g_csrf_token` cookie vs. form-body validation.297298* **Recipe 3 — Pattern C (Browser-Based Ephemeral In-Memory SPA with Native299 GIS Nonce) [Fallback]**: Load300 [references/in_memory_spa_nonce.md](references/in_memory_spa_nonce.md) for301 WebCrypto `nonce` generation (`google.accounts.id.initialize({ client_id,302 nonce: clientNonce })`), UTF-8 safe Base64URL JWT decoding, and private303 closure token management.304305* **Recipe 4 — Pattern D (Browser-Based WebCrypto Encrypted IndexedDB for306 Offline PWAs) [Fallback]**: Load307 [references/offline_pwa_encryption.md](references/offline_pwa_encryption.md)308 for non-extractable (`extractable: false`) `AES-GCM` `CryptoKey` generation309 and encrypted `IndexedDB` storage.310311* **Recipe 5 — Embedded Cross-Origin Contexts (`gsi/intermediate`)**: Load312 [references/intermediate_iframe.md](references/intermediate_iframe.md) for313 `<div id="g_id_intermediate_iframe">`, `allow="identity-credentials-get"`,314 and strict `window.postMessage` origin verification.315316--------------------------------------------------------------------------------317318## 5. Sign-Out & Account Revocation Across All Patterns319320```javascript321export function handleSignOut(userEmail) {322 // 1. Disable client-side One Tap auto-selection323 google.accounts.id.disableAutoSelect();324325 // 2. Revoke OAuth grant if user disconnected account326 if (userEmail) {327 google.accounts.id.revoke(userEmail, () => {328 console.log('User grant revoked');329 });330 }331332 // 3. Clear storage / session333 AuthManager.clear(); // Pattern C334 fetch('/api/auth/logout', { method: 'POST' }); // Pattern A335}336```337338--------------------------------------------------------------------------------339340## 6. References & Normative Standards341342* [RFC 7519: JSON Web Token (JWT)](https://datatracker.ietf.org/doc/html/rfc7519)343 — Standard claims (`iss`, `sub`, `aud`, `exp`, `iat`, `nonce`), formatting,344 and processing rules.345346* [RFC 7515: JSON Web Signature (JWS)](https://datatracker.ietf.org/doc/html/rfc7515)347 — Cryptographic signature verification against Google's public JWK certs348 (`https://www.googleapis.com/oauth2/v3/certs`).349350* [RFC 4648 § 5: Base64url Encoding](https://datatracker.ietf.org/doc/html/rfc4648#section-5)351 — URL-safe Base64 encoding without padding used across JWT segments.352353* [IETF OAuth 2.0 Browser-Based Applications](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps)354 — Normative architecture standards (§ 6.1 BFF, § 6.2 TMB, § 6.3355 Client-side).356357* [Google Identity Services Web Reference](https://developers.google.com/identity/gsi/web/reference/js-reference)358 — Official GIS API reference.359360* [Intermediate Iframe API Reference](https://developers.google.com/identity/gsi/web/amp/nonamp-reference)361 — Cross-origin iframe embedding guide.362363* [Verify ID Tokens Server-Side](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token)364 — Server-side token verification protocols.365366* [W3C Federated Credential Management API (FedCM)](https://www.w3.org/TR/fedcm-1/)367 — Browser identity credential mediation standard.368369* [W3C Web Cryptography API](https://www.w3.org/TR/WebCryptoAPI/) —370 Non-extractable key generation (`extractable: false`) and AES-GCM standards.