Sign In With Google Web
GoogleOfficialPublished by Google
- Skill
- Tool integration
- Automation and integrations
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides normative architectural patterns, security directives, and implementation recipes for integrating Sign In With Google (SiwG) via the Google Identity Services (GIS) Web SDK. It emphasizes secure authentication flows, including Backend For Frontend (BFF) and Token-Mediating Backend (TMB) patterns, while providing guidance on CSP, COOP, and Permissions Policy headers. The skill covers client-side integration for various web frameworks and provides specific recipes for token verification, nonce management, and secure session handling.
What it does
- Provides architectural patterns for secure Google authentication integration.
- Details backend-mediated token verification and session management.
- Offers implementation recipes for React, Next.js, and general web architectures.
- Defines security directives for CSP, COOP, and Permissions Policy headers.
- Provides guidance on handling sign-out, revocation, and auto-selection lifecycles.
- Includes patterns for secure client-side storage and nonce validation.
When to use it
- When implementing Google sign-in buttons or One Tap prompts in web applications.
- When building secure authentication flows that require backend token verification.
- When configuring web security headers to support GIS functionality.
- When migrating from legacy Google Sign-In (gapi.auth2) to modern Google Identity Services.
- When embedding Google sign-in features within cross-origin iframes.
Advantages
- Aligns implementations with IETF OAuth 2.0 standards for browser-based applications.
- Promotes secure patterns that mitigate XSS token harvesting risks.
- Provides deterministic patterns for dynamic script loading in modern SPAs.
- Offers clear guidance on avoiding deprecated legacy authentication libraries.
Usage examples
- “How do I implement the Backend For Frontend pattern for Google sign-in in a FastAPI application?”
- The agent provides the implementation recipe for Pattern A, including the frontend GIS initialization and the backend token verification logic using the Google auth library.
- “What security headers are required for Google Identity Services to function correctly?”
- The agent lists the necessary CSP, COOP, and Permissions Policy directives, including specific values like same-origin-allow-popups and identity-credentials-get.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/google/sign-in-with-google-web/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip sign-in-with-google-web.zip -d .agents/skills
Documentation by Google
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.
Files
- ATTRIBUTION.mdAdded by AutoGineer867 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md17.1 KiB
- references/bff_fastapi_verification.md3.4 KiB
- references/in_memory_spa_nonce.md3.1 KiB
- references/intermediate_iframe.md1.9 KiB
- references/offline_pwa_encryption.md3.9 KiB
- references/tmb_login_uri_redirect.md2.7 KiB
references/bff_fastapi_verification.md
Pattern A: Backend For Frontend (BFF) Verification Recipe (Python / FastAPI)
This reference provides the complete implementation recipe for Pattern A
(Backend For Frontend — IETF draft-ietf-oauth-browser-based-apps § 6.1), the
recommended gold-standard architecture for full-stack SPAs and web applications.
1. Custom UI Button & Programmatic Prompting Pattern (Frontend)
When triggering Google Identity Services (GIS) from a custom application button
(rather than renderButton):
export function setupCustomGoogleSignIn(
buttonEl: HTMLElement,
clientId: string,
onCredentialReceived: (credential: string) => void
) {
// 1. Initialize GIS with callback and popup configuration
google.accounts.id.initialize({
client_id: clientId,
callback: (res: { credential: string }) => {
if (res.credential) {
onCredentialReceived(res.credential);
}
},
ux_mode: 'popup',
auto_select: false,
});
// 2. Programmatically trigger One Tap / popup prompt on user click
buttonEl.addEventListener('click', () => {
google.accounts.id.prompt((notification) => {
if (notification.isNotDisplayed()) {
console.warn(
'One Tap prompt not displayed:',
notification.getNotDisplayedReason()
);
}
});
});
}2. FastAPI BFF Token Verification & Session Issuance (Backend)
from fastapi import Cookie, FastAPI, HTTPException, Response
from google.auth.transport import requests
from google.oauth2 import id_token
from pydantic import BaseModel
app = FastAPI()
GOOGLE_CLIENT_ID = "YOUR_CLIENT_ID.apps.googleusercontent.com"
ALLOWED_WORKSPACE_DOMAIN = "mycompany.com" # Optional hd restriction
class AuthRequest(BaseModel):
credential: str
@app.post("/api/auth/google")
async def authenticate_google(
auth_req: AuthRequest,
response: Response,
auth_nonce_cookie: str | None = Cookie(None, alias="auth_nonce"),
):
try:
# 1. Cryptographically verify signature and audience against Google Public JWKs
id_info = id_token.verify_oauth2_token(
auth_req.credential, requests.Request(), GOOGLE_CLIENT_ID
)
# 2. Verify nonce strictly against server session/HTTP-only cookie state (Replay Protection)
if auth_nonce_cookie and id_info.get("nonce") != auth_nonce_cookie:
raise HTTPException(
status_code=401, detail="Nonce mismatch / token replay detected"
)
# 3. Verify Google Workspace Hosted Domain claim if enforcing domain lock
if (
ALLOWED_WORKSPACE_DOMAIN
and id_info.get("hd") != ALLOWED_WORKSPACE_DOMAIN
):
raise HTTPException(
status_code=403, detail="Unauthorized workspace domain"
)
user_sub = id_info["sub"]
user_email = id_info["email"]
# 4. Create session & set secure HttpOnly cookie
response.set_cookie(
key="session_id",
value=create_server_session(user_sub, user_email),
httponly=True,
secure=True,
samesite="lax",
)
# Clear temporary nonce cookie after successful verification
response.delete_cookie("auth_nonce")
return {"status": "authenticated", "email": user_email}
except ValueError as e:
raise HTTPException(status_code=401, detail="Invalid token") from eRequirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Publisher
- Google (Official)
- Source
- google/skills · skills/identity/sign-in-with-google-web · commit 2194d3b
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Google or Google.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download sign-in-with-google-web.zip