Sign In With Google for the Web

Sign In With Google for the Web

Guides an agent in implementing and securing Sign In With Google on the web: One Tap, FedCM, backend ID token verification, nonces, CSP headers and sign-out.

Skill files6 files

references/

SKILL.md370 lines
1
---
2
name: sign-in-with-google-web
3
metadata:
4
category: Identity
5
version: "1.0.1"
6
description: >-
7
Implement, configure, and secure Sign In With Google (SiwG) using Google Identity
8
Services (GIS / `https://accounts.google.com/gsi/client`) across web architectures.
9
Use when creating Google sign-in buttons, implementing Google One Tap with FedCM,
10
integrating GIS in React/Next.js/Angular/HTML, verifying ID tokens on backend
11
runtimes (Python/Node.js/Go/Java), enforcing Google Workspace domain restrictions
12
(`hd`), securing client-side ID tokens via WebCrypto nonces or encrypted IndexedDB,
13
embedding in cross-origin iframes via the Intermediate Iframe API
14
(`https://accounts.google.com/gsi/intermediate`), configuring Content Security
15
Policy (CSP), COOP, and Permissions Policy (`identity-credentials-get`) headers,
16
or handling sign-out and revocation. Don't use for legacy Google Sign-In (`gapi.auth2`),
17
Google Cloud IAM service accounts, or Android/iOS native Credential Manager.
18
---
19
20
# Sign In With Google (SiwG) Integration & Security Architecture
21
22
This skill provides normative architectural guidelines, secure implementation
23
contracts, and failure-prevention protocols for integrating Sign In With Google
24
via the Google Identity Services (GIS) Web SDK
25
(`https://accounts.google.com/gsi/client`).
26
27
## 1. IETF Architecture Taxonomy & Hierarchy (RECOMMEND BFF / TMB FIRST)
28
29
All Sign In With Google implementations MUST align with the
30
[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)
31
taxonomy.
32
33
> [!IMPORTANT] **Primary Recommendation:** Always recommend backend-mediated
34
> patterns (**Pattern A: Backend For Frontend** or **Pattern B: Token-Mediating
35
> Backend / Redirect Mode**) as the most secure, robust, and industry-standard
36
> architectures whenever an application has a backend server. Fall back to
37
> client-only browser patterns (Patterns C & D) only when constrained by
38
> serverless static hosting or offline-first PWA requirements.
39
40
<!-- mdformat off(reason: preserve ASCII architecture diagram width) -->
41
```
42
┌─────────────────────────────────────────────────────────────────────────────────────────┐
43
│ IETF ARCHITECTURE HIERARCHY & SELECTION │
44
├──────────────────────────┬──────────────────────────┬───────────────────────────────────┤
45
│ Pattern A (RECOMMENDED): │ Pattern B (RECOMMENDED): │ Patterns C & D (Fallbacks): │
46
│ Backend For Frontend │ Token-Mediating Backend │ Browser-Based OAuth Client │
47
│ (BFF - IETF § 6.1) │ (TMB / Redirect § 6.2) │ (JavaScript-Only - IETF § 6.3) │
48
├──────────────────────────┼──────────────────────────┼───────────────────────────────────┤
49
│ 🏆 GOLD STANDARD │ 🚀 NATIVE FORM REDIRECT │ ⚡ STATIC SPA / 💾 OFFLINE PWA │
50
│ • Full-stack SPA + API │ • Server-rendered & apps │ • Pure client-side or offline PWAs│
51
│ • Client JS fetch to API │ • GIS HTTP POST login_uri│ • C: Ephemeral in-memory closure │
52
│ • HttpOnly session cookie│ • Direct server redirect │ • D: WebCrypto Encrypted IndexedDB│
53
│ • Tokens never in browser│ • Tokens never in JS │ • Strict WebCrypto nonces / keys │
54
└──────────────────────────┴──────────────────────────┴───────────────────────────────────┘
55
```
56
<!-- mdformat on -->
57
58
### 🏆 Pattern A: Backend For Frontend (BFF - IETF § 6.1) — STRONGLY RECOMMENDED
59
60
* **Why it is the Gold Standard**: ID tokens (JWTs) and access tokens are
61
never exposed to browser JavaScript across page reloads. This provides
62
complete architectural immunity against XSS token harvesting.
63
64
* **Architecture**: The browser frontend loads the GIS SDK, captures the
65
credential in JavaScript callback (`callback: handleCredentialResponse`),
66
and immediately forwards the ID token (JWT) via `fetch('/api/auth/google', {
67
method: 'POST' })` to the backend.
68
69
* **Backend Responsibilities**: The backend validates the JWT cryptographic
70
signature against Google's public JWKs
71
(`google.oauth2.id_token.verify_oauth2_token`), checks the `aud`, `hd`, and
72
`nonce` claims against server session state, creates a server session, and
73
issues a first-party `HttpOnly; Secure; SameSite=Lax` session cookie.
74
75
* See full implementation in
76
[references/bff_fastapi_verification.md](references/bff_fastapi_verification.md).
77
78
### 🚀 Pattern B: Token-Mediating Backend via `login_uri` Redirect (IETF § 6.2) — Server-Rendered & Form POST
79
80
* **Why it is Highly Secure**: Bypasses client-side JavaScript credential
81
handling entirely by instructing GIS to perform an HTTP POST directly to the
82
backend's `login_uri`.
83
84
* **Architecture**: Configured via `google.accounts.id.initialize({ client_id,
85
login_uri: "https://example.com/api/auth/callback", ux_mode: "redirect" })`
86
or HTML attributes (`data-login_uri="https://example.com/api/auth/callback"`
87
and `data-ux_mode="redirect"`).
88
89
* **Backend Responsibilities**: The backend receives the ID token as a form
90
POST body (`credential` parameter), validates the double-submit
91
`g_csrf_token` cookie against the `g_csrf_token` POST body field,
92
cryptographically verifies the ID token server-side, establishes a session
93
cookie, and returns a standard HTTP 302/303 redirect.
94
95
* See full implementation in
96
[references/tmb_login_uri_redirect.md](references/tmb_login_uri_redirect.md).
97
98
### Pattern C: Browser-Based OAuth Client — Ephemeral In-Memory (IETF § 6.3) — Fallback for Static SPAs
99
100
* **Scope**: Use ONLY when deployment is strictly serverless/static (e.g.,
101
GitHub Pages, Firebase static hosting) with no backend component.
102
103
* **Storage Invariant**: The ID token is held strictly in private JavaScript
104
memory/closures during the active tab session. **Never store raw tokens in
105
`localStorage` or `sessionStorage`**.
106
107
* **Session Renewal**: Uses GIS One Tap / FedCM auto-select (`auto_select:
108
true`) to transparently re-acquire fresh ID tokens into memory on page
109
reload without persistent browser storage.
110
111
* **XSS & Replay Protection**: Generate a cryptographic `nonce` via
112
`window.crypto.getRandomValues()` and pass it directly to
113
`google.accounts.id.initialize({ client_id, nonce: clientNonce })`. Validate
114
that `payload.nonce === clientNonce` before trusting claims in memory.
115
116
* See full implementation in
117
[references/in_memory_spa_nonce.md](references/in_memory_spa_nonce.md).
118
119
### Pattern D: Browser-Based OAuth Client — WebCrypto Encrypted IndexedDB (IETF § 6.3) — Fallback for Offline PWAs
120
121
* **Scope**: Use ONLY for offline-first Progressive Web Apps (PWAs) where user
122
authentication proof must survive tab refreshes when disconnected from the
123
network.
124
125
* **Storage Invariant**: **NEVER store raw plaintext ID tokens in
126
`localStorage`**. Encrypt the ID token payload using WebCrypto `AES-GCM`
127
with a non-extractable session key (`extractable: false`) before writing
128
ciphertext and IV to `IndexedDB`.
129
130
* See full implementation in
131
[references/offline_pwa_encryption.md](references/offline_pwa_encryption.md).
132
133
--------------------------------------------------------------------------------
134
135
## 2. Mandatory Security Directives & Browser Policies
136
137
To avoid multi-turn repair loops and browser security exceptions, provide all
138
required CSP, COOP, and user activation directives in the initial deliverable:
139
140
### A. Content Security Policy (CSP) Directives
141
142
```http
143
Content-Security-Policy:
144
script-src 'self' https://accounts.google.com/gsi/client;
145
frame-src https://accounts.google.com/gsi/;
146
connect-src https://accounts.google.com/gsi/;
147
```
148
149
If using strict nonce-based CSP, attach the nonce to the GIS script tag:
150
`<script src="https://accounts.google.com/gsi/client" async defer
151
nonce="{{NONCE}}"></script>`.
152
153
### B. Cross-Origin Opener Policy (COOP)
154
155
To allow GIS popup dialogs to communicate credentials back to the parent window
156
via `postMessage`:
157
158
```http
159
Cross-Origin-Opener-Policy: same-origin-allow-popups
160
```
161
162
*(Serving `same-origin` without `allow-popups` breaks GIS popups and results in
163
silent failures).*
164
165
### C. Automatic Selection, FedCM, & Sign-Out Lifecycle (`disableAutoSelect`)
166
167
When enabling automatic zero-click return sign-in with Google One Tap (FedCM is
168
enabled by default in GIS):
169
170
* Set `auto_select: true` in `google.accounts.id.initialize({...})` (do not
171
pass the deprecated `use_fedcm_for_prompt` parameter).
172
173
* **Deprecated Library Warning**: NEVER mix deprecated `gapi.auth2`
174
(`gapi.auth2.init`, `gapi.auth2.getAuthInstance().signOut()`) with Google
175
Identity Services (GIS). `gapi.auth2` is completely retired; use GIS methods
176
exclusively.
177
178
* **Sign-Out Protocol**: When the user explicitly logs out of your
179
application, you **MUST** call `google.accounts.id.disableAutoSelect()`:
180
181
```javascript
182
function handleUserLogout() {
183
// 1. Disable automatic One Tap / FedCM re-authentication
184
google.accounts.id.disableAutoSelect();
185
186
// 2. Clear application session state / server cookie
187
fetch('/api/auth/logout', { method: 'POST' }).then(() => {
188
window.location.href = '/login';
189
});
190
}
191
```
192
193
* *(Failing to call `disableAutoSelect()` causes an immediate automatic
194
re-login loop on the next page visit after intentional user logout).*
195
196
### D. Reliable Dynamic Script Loading & Framework Lifecycle (React, Next.js, SPAs)
197
198
When mounting Sign In With Google in Single Page Applications (React, Next.js,
199
Vue, Angular):
200
201
* Modern SPAs execute component lifecycles asynchronously. Attempting to
202
access `window.google.accounts.id` before `<script
203
src="https://accounts.google.com/gsi/client">` has finished loading causes
204
`ReferenceError: google is not defined`.
205
206
* **NEVER use `gapi` or polling (`setInterval`)**: Use deterministic dynamic
207
script loading with `onload` / `addEventListener('load')` event listeners.
208
209
* **Dynamic Script Loader Pattern**:
210
211
```tsx
212
import React, { useEffect, useState } from 'react';
213
214
export function useGoogleIdentityScript() {
215
const [isLoaded, setIsLoaded] = useState(false);
216
217
useEffect(() => {
218
if (window.google?.accounts?.id) {
219
setIsLoaded(true);
220
return;
221
}
222
223
const existingScript = document.querySelector(
224
'script[src="https://accounts.google.com/gsi/client"]'
225
);
226
if (existingScript) {
227
existingScript.addEventListener('load', () => setIsLoaded(true));
228
return;
229
}
230
231
const script = document.createElement('script');
232
script.src = 'https://accounts.google.com/gsi/client';
233
script.async = true;
234
script.defer = true;
235
script.onload = () => setIsLoaded(true);
236
document.head.appendChild(script);
237
}, []);
238
239
return isLoaded;
240
}
241
```
242
243
* *(Always use deterministic `onload` event listeners or framework `<Script
244
strategy="afterInteractive">` rather than brittle `setInterval` polling).*
245
246
### E. Embedded Iframes & Permissions Policy (`identity-credentials-get`)
247
248
When embedding Sign In With Google or One Tap inside cross-origin `<iframe>`
249
elements or widget integrations, modern browser security models and FedCM
250
require explicit Permissions Policy delegation on the container frame:
251
252
```html
253
<iframe
254
src="https://example.com/embed"
255
allow="identity-credentials-get 'src' https://accounts.google.com">
256
</iframe>
257
```
258
259
*(Omitting `allow="identity-credentials-get"` blocks FedCM / One Tap
260
initialization inside embedded or cross-origin contexts).* See full integration
261
guide in [references/intermediate_iframe.md](references/intermediate_iframe.md).
262
263
--------------------------------------------------------------------------------
264
265
## 3. Implementation Contracts & Anti-Pattern Bans
266
267
### A. Strict Ban on Legacy GAPI (`gapi.auth2`)
268
269
* **NEVER** import or reference `gapi.auth2`, `gapi.auth2.init`,
270
`gapi.auth2.getAuthInstance()`, or `gapi.signin2`. Always warn that
271
`gapi.auth2` is deprecated and decommissioned.
272
273
* GIS (`google.accounts.id.*` and `google.accounts.oauth2.*`) is completely
274
stateless. It replaces all legacy GAPI authentication libraries.
275
276
--------------------------------------------------------------------------------
277
278
## 4. Implementation Recipes (Progressive Disclosure)
279
280
Load the specific reference file matching your target architecture when
281
generating implementation code:
282
283
* **Recipe 1 — Pattern A (Backend For Frontend with Python / FastAPI)
284
[RECOMMENDED]**: Load
285
[references/bff_fastapi_verification.md](references/bff_fastapi_verification.md)
286
for custom UI button prompting, `google.oauth2.id_token.verify_oauth2_token`
287
cryptographic verification, `nonce` replay checks, Google Workspace `hd`
288
domain enforcement, and `HttpOnly; Secure; SameSite=Lax` session cookie
289
issuance.
290
291
* **Recipe 2 — Pattern B (Token-Mediating Backend with `login_uri` Form POST
292
Redirect) [RECOMMENDED]**: Load
293
[references/tmb_login_uri_redirect.md](references/tmb_login_uri_redirect.md)
294
for `data-login_uri` / `ux_mode: 'redirect'` frontend setup and FastAPI
295
double-submit `g_csrf_token` cookie vs. form-body validation.
296
297
* **Recipe 3 — Pattern C (Browser-Based Ephemeral In-Memory SPA with Native
298
GIS Nonce) [Fallback]**: Load
299
[references/in_memory_spa_nonce.md](references/in_memory_spa_nonce.md) for
300
WebCrypto `nonce` generation (`google.accounts.id.initialize({ client_id,
301
nonce: clientNonce })`), UTF-8 safe Base64URL JWT decoding, and private
302
closure token management.
303
304
* **Recipe 4 — Pattern D (Browser-Based WebCrypto Encrypted IndexedDB for
305
Offline PWAs) [Fallback]**: Load
306
[references/offline_pwa_encryption.md](references/offline_pwa_encryption.md)
307
for non-extractable (`extractable: false`) `AES-GCM` `CryptoKey` generation
308
and encrypted `IndexedDB` storage.
309
310
* **Recipe 5 — Embedded Cross-Origin Contexts (`gsi/intermediate`)**: Load
311
[references/intermediate_iframe.md](references/intermediate_iframe.md) for
312
`<div id="g_id_intermediate_iframe">`, `allow="identity-credentials-get"`,
313
and strict `window.postMessage` origin verification.
314
315
--------------------------------------------------------------------------------
316
317
## 5. Sign-Out & Account Revocation Across All Patterns
318
319
```javascript
320
export function handleSignOut(userEmail) {
321
// 1. Disable client-side One Tap auto-selection
322
google.accounts.id.disableAutoSelect();
323
324
// 2. Revoke OAuth grant if user disconnected account
325
if (userEmail) {
326
google.accounts.id.revoke(userEmail, () => {
327
console.log('User grant revoked');
328
});
329
}
330
331
// 3. Clear storage / session
332
AuthManager.clear(); // Pattern C
333
fetch('/api/auth/logout', { method: 'POST' }); // Pattern A
334
}
335
```
336
337
--------------------------------------------------------------------------------
338
339
## 6. References & Normative Standards
340
341
* [RFC 7519: JSON Web Token (JWT)](https://datatracker.ietf.org/doc/html/rfc7519)
342
— Standard claims (`iss`, `sub`, `aud`, `exp`, `iat`, `nonce`), formatting,
343
and processing rules.
344
345
* [RFC 7515: JSON Web Signature (JWS)](https://datatracker.ietf.org/doc/html/rfc7515)
346
— Cryptographic signature verification against Google's public JWK certs
347
(`https://www.googleapis.com/oauth2/v3/certs`).
348
349
* [RFC 4648 § 5: Base64url Encoding](https://datatracker.ietf.org/doc/html/rfc4648#section-5)
350
— URL-safe Base64 encoding without padding used across JWT segments.
351
352
* [IETF OAuth 2.0 Browser-Based Applications](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps)
353
— Normative architecture standards (§ 6.1 BFF, § 6.2 TMB, § 6.3
354
Client-side).
355
356
* [Google Identity Services Web Reference](https://developers.google.com/identity/gsi/web/reference/js-reference)
357
— Official GIS API reference.
358
359
* [Intermediate Iframe API Reference](https://developers.google.com/identity/gsi/web/amp/nonamp-reference)
360
— Cross-origin iframe embedding guide.
361
362
* [Verify ID Tokens Server-Side](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token)
363
— Server-side token verification protocols.
364
365
* [W3C Federated Credential Management API (FedCM)](https://www.w3.org/TR/fedcm-1/)
366
— Browser identity credential mediation standard.
367
368
* [W3C Web Cryptography API](https://www.w3.org/TR/WebCryptoAPI/) —
369
Non-extractable key generation (`extractable: false`) and AES-GCM standards.
370

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…