Writing Sign-In With Google and Other OAuth Login Code With LLMs in November 2026: Use PKCE and a State Check, Verify the ID Token, and Key Accounts on the Provider's User ID
"Add Sign in with Google" is one of the most common things people ask an LLM to build, and the model will happily produce a working button in a few minutes. The trouble is that "working" here means "it logs me in when I click it." It does not mean the code rejects a forged callback, refuses a token meant for another app, or stops a stranger from taking over an existing account because they control a matching email address. Those failures do not show up in a demo. They show up later, in someone else's hands.
This guide walks through how to use an LLM to write social login code (Google, GitHub, Microsoft, Apple, or any OpenID Connect provider) that is safe as well as convenient. The model is useful for the plumbing. You stay responsible for four decisions it tends to get wrong on its own.
The flow in one paragraph
Almost every modern "Sign in with X" button uses the OAuth 2.0 authorization code flow, usually with OpenID Connect (OIDC) on top. Your app sends the user to the provider with a few parameters. The user signs in there and approves. The provider redirects back to your callback URL with a short-lived code. Your server exchanges that code (plus proof it started the flow) for tokens. With OIDC, one of those tokens is an ID token: a signed JWT that says who the user is. Your server checks it, finds or creates the matching local account, and starts a normal session.
Every security problem in social login sits in one of those hand-offs. That is where to aim your review.
An ID token is a sealed letter: trust it only after you check the seal and who it was addressed to. Image: Wax seal with impression of uppercase letter A by Contrafool, CC BY-SA 3.0, via Wikimedia Commons.
Rule 1: Use a maintained library, not hand-rolled HTTP
If you ask a model to "implement Google OAuth," it may write raw fetch calls to the authorization and token endpoints and decode the JWT with a base64 split. That code usually skips signature verification entirely. Decoding a JWT is not verifying it.
Tell the model which library to use. Good choices depend on your stack: Auth.js or openid-client in Node, Authlib in Python, Spring Security's OAuth2 client in Java, the framework's built-in OIDC middleware in ASP.NET Core. A good prompt looks like this:
I am adding "Sign in with Google" to a Flask app.
Use Authlib's Flask OAuth client with Google's OIDC discovery URL.
Use the authorization code flow with PKCE (S256).
Verify the ID token with the library, not by hand.
After login, create my own server-side session (I already have one,
see session.py below) and do not store provider tokens in the browser.
Show me the routes, the config, and the exact callback URL I must
register with Google. Do not invent config keys; if you are unsure of
an option name, say so.
Then check the generated calls against the library's current documentation. LLMs often mix up major versions of auth libraries, and an option that silently does nothing in the new version is worse than an error.
Rule 2: Use PKCE and a state check on every login
Two parameters protect the round trip, and the model should generate both by default. If it leaves either out, ask for them explicitly.
state
Before redirecting the user, generate a random value, store it in the user's session (or a short-lived, HttpOnly, signed cookie), and send it as the state parameter. On the callback, compare the returned state with the stored one and reject the request if they do not match or if nothing was stored. This stops an attacker from making your user's browser complete a login the attacker started, which can silently sign the victim into the attacker's account.
PKCE
PKCE (Proof Key for Code Exchange) means your app creates a random code_verifier, sends a hash of it (code_challenge with method S256) with the login request, and later sends the original verifier when it exchanges the code. A stolen authorization code is useless without the verifier. PKCE was first aimed at mobile apps, but the IETF's OAuth security best-practice guidance (RFC 9700) recommends it for confidential server-side clients too. Use it everywhere.
nonce
With OIDC, also send a random nonce, store it, and confirm that the ID token contains the same value. Most libraries handle this if you let them. Check that yours actually compares it, rather than just generating it.
What to look for in the generated code:
- The state, verifier, and nonce come from a cryptographically secure random source (for example
secrets.token_urlsafein Python orcrypto.randomBytesin Node), notMath.randomor a timestamp. - Each value is single-use: deleted from the session as soon as the callback reads it.
- A missing stored value is treated as a failure, not skipped. A common bug is
if stored_state and stored_state != returned_state, which passes when nothing was stored.
Rule 3: Lock down the redirect and callback
Register the exact callback URL with the provider, for example https://app.example.com/auth/google/callback. Avoid wildcard or prefix matches when the provider offers them. If an attacker can make the provider redirect a valid code to a URL they control, the rest of your checks may never run.
Two related traps that models often write into the callback handler:
- Open redirects after login. It is handy to send users back to the page they came from with something like
?next=/billing. If the code redirects to whatevernextcontains, an attacker can craft a login link that ends at their phishing site. Allow only relative paths on your own site, and reject anything starting with//or containing a scheme. - Leaking the code. Do not log full callback URLs, and do not render third-party scripts on the callback page. Exchange the code and redirect immediately.
Rule 4: Verify the ID token properly
When you have an ID token, the library should check all of these. Ask the model to point to the line or option that does each one:
- Signature, using the provider's published keys (the JWKS from the discovery document), with the expected algorithm. Never accept
alg: none. - Issuer (
iss) equals the provider you expect, such ashttps://accounts.google.com. - Audience (
aud) equals your client ID. A token issued to some other app by the same provider must be rejected. This check is the one hand-written code most often forgets. - Expiry (
exp) is in the future, with only a small clock-skew allowance. - Nonce matches the one you stored.
Be especially careful if your app accepts ID tokens sent from a mobile app or a JavaScript front end (for example, Google's One Tap button posts a credential to your backend). In that case your server did not fetch the token itself, so signature and audience checks are the only thing standing between you and a forged or borrowed token.
Rule 5: Key accounts on the provider's user ID, not the email
This is the decision LLMs get wrong most often, and the one with the worst consequences. A typical generated callback looks like this:
# Risky: finds the account by email alone
user = db.users.find_one(email=claims["email"])
if not user:
user = db.users.create(email=claims["email"])
login(user)
Email addresses are a poor identity key for login. They can change, they can be reassigned, and depending on the provider they are not always verified. Microsoft, for example, has warned developers that the email claim in its Entra ID tokens should not be used for authorization decisions, because it is not guaranteed to be verified for every account.
The stable identifier is the combination of issuer and subject: (iss, sub). The sub claim is the provider's permanent ID for that user within that issuer. Store it in a separate table:
CREATE TABLE login_identities (
provider TEXT NOT NULL, -- e.g. the iss value
subject TEXT NOT NULL, -- the sub claim
user_id BIGINT NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (provider, subject)
);
The callback logic then becomes:
- Look up
(iss, sub)inlogin_identities. If found, log in that user. Done. - If not found and no local account uses this email, create a new user and a new identity row.
- If not found but a local account already uses this email, do not link automatically. Ask the user to sign in to the existing account the usual way first (password, magic link, or the other provider), then link the new provider from their settings page.
Step 3 feels like friction, but it closes a real hole. Without it, anyone who can get a provider to issue a token with your user's email address, whether through an unverified email claim, a misconfigured provider, or a recycled address, can walk straight into that account. If you decide to auto-link anyway, at minimum require email_verified to be true and only trust it from providers you know verify email ownership.
A good front desk hands a room key to the guest on the booking, not to anyone who knows the guest's name. Image: Reception desk at Balch Hotel in Dufur, Oregon by Mattsjc, CC BY 4.0, via Wikimedia Commons.
Rule 6: After login, it is your session, not their token
Once you have verified who the user is, the provider's job is finished. Models sometimes store the access token or ID token in localStorage and send it on every API call to your own backend. Don't. Start your own server-side session the same way your password login does: set a fresh session ID in a cookie with HttpOnly, Secure, and an appropriate SameSite setting, and rotate the session ID at login.
Only keep the provider's access or refresh token if you actually call the provider's API later (for example, reading a user's calendar). If you do:
- Request the smallest scopes you need. For plain login,
openid email profileis enough. Ask the model to justify every extra scope. - Store refresh tokens on the server, encrypted at rest, never in the browser.
- Keep the client secret in an environment variable or secret manager, out of the repository and out of front-end bundles.
Test the failure paths, not just the happy path
Clicking the button and landing on your dashboard proves very little. Ask the model to write tests (or a manual checklist) for each of these, then run them:
- Callback with a
statethat does not match, and with no stored state at all. Both must fail. - Callback that reuses an authorization code that was already exchanged. The provider should reject it, and your code should show an error rather than crash.
- An ID token with the wrong
aud, an expiredexp, or a wrongnonce. Many libraries let you build test tokens signed with a local key for this. - A login where the email matches an existing password account. It must not log in to that account without the linking step.
- A login with
email_verifiedset to false. - A
nextparameter pointing tohttps://evil.exampleor//evil.example. You must stay on your own site. - A user who removes your app's access in their provider account settings, then tries to log in again. The flow should simply ask for consent again.
If the model writes a test that only mocks the library to return "valid user," that test is checking the mock. Make sure at least the state, audience, and account-linking tests run against your real callback handler.
A review checklist for generated login code
- Uses a maintained OAuth/OIDC library at a version whose docs you checked.
- Authorization code flow with PKCE (S256), plus
stateandnonce, each random and single-use. - Exact callback URL registered; post-login redirects limited to your own relative paths.
- ID token signature, issuer, audience, expiry, and nonce are verified.
- Accounts keyed on
(iss, sub); no automatic linking to existing accounts by email alone. - Your own session cookie after login, rotated at sign-in; no provider tokens in the browser.
- Minimal scopes; client secret and any refresh tokens kept server-side.
- Tests cover forged state, wrong audience, expired token, and the existing-email case.
Bottom line
An LLM can save you an afternoon of reading OAuth documentation and wiring routes. It will not, on its own, decide how accounts should be linked or which checks are non-negotiable. Give it the library, ask for PKCE, state, and nonce by name, insist that it verify the ID token's audience, and key every account on the provider's user ID instead of the email address. Then try to break the flow yourself before anyone else does.
Comments
Post a Comment