Google 网页登录集成
sign-in-with-google-web
使用 Google Identity Services(GIS,`https://accounts.google.com/gsi/client`)在各种 Web 架构中实现、配置并保护 Google 登录(Sign In With Google,SiwG)。适用于创建 Google 登录按钮、通过 FedCM 实现 Google One Tap、在 React/Next.js/Angular/HTML 中集成 GIS、在后端运行时(Python/Node.js/Go/Java)验证 ID token、强制实施 Google Workspace 域名限制(`hd`)、通过 WebCrypto nonce 或加密的 IndexedDB 保护客户端 ID token、通过 Intermediate Iframe API(`https://accounts.google.com/gsi/intermediate`)嵌入跨域 iframe、配置内容安全策略(CSP)、COOP 和 Permissions Policy(`identity-credentials-get`)响应头,或处理退出登录与授权撤销。不适用于旧版 Google Sign-In(`gapi.auth2`)、Google Cloud IAM 服务账号,或 Android/iOS 原生 Credential Manager。
- License 许可
- Apache-2.0
- 所属仓库
- google/skills
- 最近更新
- 2026-11-14
- Stars
- ★ 2.4w
- Forks
- 2.0k
01 前言 Front Matter
- name
- sign-in-with-google-web
- metadata
- { "version": "1.0.0", "category": "Identity" }
- description
- Implement, configure, and secure Sign In With Google (SiwG) using Google Identity Services (GIS / `https://accounts.google.com/gsi/client`) across web architectures. Use when creating Google sign-in buttons, implementing Google One Tap with FedCM, integrating GIS in React/Next.js/Angular/HTML, verifying ID tokens on backend runtimes (Python/Node.js/Go/Java), enforcing Google Workspace domain restrictions (`hd`), securing client-side ID tokens via WebCrypto nonces or encrypted IndexedDB, embedding in cross-origin iframes via the Intermediate Iframe API (`https://accounts.google.com/gsi/intermediate`), configuring Content Security Policy (CSP), COOP, and Permissions Policy (`identity-credentials-get`) headers, or handling sign-out and revocation. Don't use for legacy Google Sign-In (`gapi.auth2`), Google Cloud IAM service accounts, or Android/iOS native Credential Manager.
02 资源文件 18
- 参考文档checklist.md9.9 KB
- 资产文件documentation-requirements.csv7.9 KB
- 参考文档instructions.md5.0 KB
- 参考文档references/bff_fastapi_verification.md3.4 KB
- 参考文档references/in_memory_spa_nonce.md3.1 KB
- 参考文档references/intermediate_iframe.md1.9 KB
- 参考文档references/offline_pwa_encryption.md3.9 KB
- 参考文档references/tmb_login_uri_redirect.md2.7 KB
- 参考文档templates/deep-dive-template.md5.7 KB
- 参考文档templates/index-template.md4.4 KB
- 参考文档templates/project-overview-template.md1.9 KB
- 参考文档templates/project-scan-report-schema.json4.7 KB
- 参考文档templates/source-tree-template.md2.1 KB
- 参考文档workflow.md534 B
- 参考文档workflows/deep-dive-instructions.md11.6 KB
- 参考文档workflows/deep-dive-workflow.md979 B
- 参考文档workflows/full-scan-instructions.md42.2 KB
- 参考文档workflows/full-scan-workflow.md970 B
03 SKILL.md 正文
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.
<!-- mdformat off(reason: preserve ASCII architecture diagram width) -->
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│ 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 │
└──────────────────────────┴──────────────────────────┴───────────────────────────────────┘
<!-- mdformat on -->
? 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) viafetch('/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 theaud,hd, andnonceclaims against server session state, creates a server session, and issues a first-partyHttpOnly; Secure; SameSite=Laxsession 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"anddata-ux_mode="redirect"). -
Backend Responsibilities: The backend receives the ID token as a form POST body (
credentialparameter), validates the double-submitg_csrf_tokencookie against theg_csrf_tokenPOST 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
localStorageorsessionStorage. -
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
nonceviawindow.crypto.getRandomValues()and pass it directly togoogle.accounts.id.initialize({ client_id, nonce: clientNonce }). Validate thatpayload.nonce === clientNoncebefore 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 WebCryptoAES-GCMwith a non-extractable session key (extractable: false) before writing ciphertext and IV toIndexedDB. -
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: trueingoogle.accounts.id.initialize({...})(do not pass the deprecateduse_fedcm_for_promptparameter). -
Deprecated Library Warning: NEVER mix deprecated
gapi.auth2(gapi.auth2.init,gapi.auth2.getAuthInstance().signOut()) with Google Identity Services (GIS).gapi.auth2is 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.idbefore<script src="https://accounts.google.com/gsi/client">has finished loading causesReferenceError: google is not defined. -
NEVER use
gapior polling (setInterval): Use deterministic dynamic script loading withonload/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
onloadevent listeners or framework<Script strategy="afterInteractive">rather than brittlesetIntervalpolling).
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(), orgapi.signin2. Always warn thatgapi.auth2is deprecated and decommissioned. -
GIS (
google.accounts.id.*andgoogle.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_tokencryptographic verification,noncereplay checks, Google Workspacehddomain enforcement, andHttpOnly; Secure; SameSite=Laxsession cookie issuance. -
Recipe 2 — Pattern B (Token-Mediating Backend with
login_uriForm POST Redirect) [RECOMMENDED]: Load references/tmb_login_uri_redirect.md fordata-login_uri/ux_mode: 'redirect'frontend setup and FastAPI double-submitg_csrf_tokencookie 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
noncegeneration (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-GCMCryptoKeygeneration and encryptedIndexedDBstorage. -
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 strictwindow.postMessageorigin 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
-
RFC 7519: JSON Web Token (JWT) — Standard claims (
iss,sub,aud,exp,iat,nonce), formatting, and processing rules. -
RFC 7515: JSON Web Signature (JWS) — Cryptographic signature verification against Google's public JWK certs (
https://www.googleapis.com/oauth2/v3/certs). -
RFC 4648 § 5: Base64url Encoding — URL-safe Base64 encoding without padding used across JWT segments.
-
IETF OAuth 2.0 Browser-Based Applications — Normative architecture standards (§ 6.1 BFF, § 6.2 TMB, § 6.3 Client-side).
-
Google Identity Services Web Reference — Official GIS API reference.
-
Intermediate Iframe API Reference — Cross-origin iframe embedding guide.
-
Verify ID Tokens Server-Side — Server-side token verification protocols.
-
W3C Federated Credential Management API (FedCM) — Browser identity credential mediation standard.
-
W3C Web Cryptography API — Non-extractable key generation (
extractable: false) and AES-GCM standards.
04 同仓库更多 Skills
cloud-operator-share-context
Shares Google Cloud operating context the user or their team already have — environments, projects, services and regions, product preferences, best practices, architecture guidance, runbooks — found in agent instruction files, local memory, skills and workflows, and the repository's GCP docs, with the operator agent's memory after the user reviews the list. Use when the user runs this skill, accepts the cloud-operator or cloud-operator-setup skill's offer to share their existing Google Cloud context, or asks to share, import or save that context or a GCP fact for the operator agent. Don't use for ordinary GCP requests, which go to the cloud-operator skill.
cloud-operator-setup
Sets up the operator agent in a Google Cloud project via the autocloud MCP server: picks the operator project, creates or checks the user's operator agent, saves the project, and offers to share the user's existing Google Cloud operating context with the operator agent's memory. Use when the user runs this skill, asks to set up the operator or create their operator agent, or chooses setup when the cloud-operator skill asks. Don't use for ordinary GCP requests or installing gcloud.
developer-device-platform-device-run
Runs automated, non-interactive jobs on remote Android devices with Developer Device Platform (DDP) Device Run using `gcloud beta device-run sessions`: native Android executables or shell scripts (for example CLI tools, custom runners, test harnesses or benchmarks) and Android instrumentation tests, on one or many devices, then waits for completion and collects per-device outputs and logs. Use when running a binary or test suite on remote devices without an interactive connection. Don't use it for interactive device reservations, adb tunnels or screen streaming (use developer-device-platform-basics), or for local devices.
compute-vm-creation
Guides the planning, configuration, and provisioning of standalone Google Compute Engine virtual machines (VMs) and bare metal (-metal) instances using gcloud CLI commands or direct MCP tool execution. Use ONLY when the user wants to create, configure, or provision a new standalone Compute Engine VM or bare metal instance from conversational intents (hardware sizing, region selection, OS image, networking, security defaults). DO NOT read or use for Google Kubernetes Engine (GKE) Autopilot or Standard clusters, Kubernetes node pools or Pods, container orchestration, managing existing VMs, Managed Instance Groups (MIGs), or Instance Templates.
agent-platform-autorater-customization
Customizes an autorater (evaluation metric) for an AI agent so its grades match the user's own judgment, starting from the agent's real trajectories. Use when a user wants a metric tailored to their agent, wants to turn failing trajectories into rubrics, says an existing autorater grades their agent wrong, or wants an autorater to agree with human labels (autorater hillclimbing, judge calibration). Don't use for quick evals with built-in metrics or for improving the agent itself (use agent-platform-eval-flywheel).
iap-agent-platform-troubleshooting
Diagnoses Identity-Aware Proxy (IAP) denials of outbound requests from Gemini Enterprise Agent Platform agents that run on Agent Runtime and send traffic through Agent Gateway. Use when an agent request fails with "Egress request is not authorized", when Cloud Audit Logs show an IAP egressViaIAP decision with granted false, when IAP audit entries are missing while debugging agent egress, or when Access policies, IAP allow policies, policy bindings, or Agent Registry entries might block agent egress. Don't use for Gemini model IAM permission errors (such as aiplatform.endpoints.predict), Agent Platform API errors, or Agent Runtime deployment or 500 errors (use agent-platform-troubleshooting instead). Don't use for setting up, creating, or connecting an Agent Gateway, or for IAP web apps, IAP TCP forwarding, or SSH.