What really happens inside 'Sign in with Google': OAuth 2.0, OpenID Connect and PKCE
An email or token arriving at your backend is not proof. The Authorization Code + PKCE flow, access token vs ID token, and verifying an ID token in Django properly: signature, aud, iss, exp.
You've added a "Sign in with Google" button to your site. The frontend developer found a quick solution: on click, the browser fetches the user's profile from Google and sends {"email": "ali@gmail.com"} to the backend. The backend looks the user up by email and opens a session. It works, and the demo looks great.
Then someone opens DevTools and replays that request with a different email. The backend happily lets them in too. No password, no Google, no checks at all.
There's also a "more careful" variant: the frontend gets a token from Google, sends it to the backend, and the backend base64-decodes it and reads email. That's nearly the same hole. In this post we'll walk through what protocol actually sits behind "Sign in with Google", which token is for what, and how to verify an ID token properly in a Django backend, step by step.
Why the naive approach breaks
The core mistake: the backend trusts a claim made by the client. The browser is an environment you don't control. Any JSON, header or token coming from it only means "someone says so". The backend needs proof: Google really issued this, issued it for your application specifically, and it hasn't expired.
There's a subtler case too: the backend accepts a token and calls a Google API with it (say, userinfo) to find out who it belongs to. The token is real, Google answers, so what's wrong? The token may have been issued to a different application. Picture this: someone builds a "Free quiz" app, thousands of people sign in to it with Google, and the author collects their tokens. If your backend reasons "Google accepted it, so it's fine", those tokens can sign in to your site as the same people. This is called token substitution, and exactly one thing protects you from it: checking who the token was issued to (aud).
OAuth 2.0 and OpenID Connect: who does what
Let's separate the terms first, because this is where the confusion starts.
OAuth 2.0 is an authorization protocol: it's about granting permissions. It answers "may this app read my Google Drive files on my behalf?". The app ends up with an access token. OAuth 2.0 by itself doesn't answer "who is this user?".
OpenID Connect (OIDC) is an authentication layer on top of OAuth 2.0. When the openid scope is requested, the provider also returns an ID token: a signed JWT saying "this is user X, I authenticated them at time T, for application A".
| ID token | Access token | |
|---|---|---|
| Audience | Your app (the client) | The resource server (API) |
| Format | Always a JWT (OIDC requires it) | Provider-defined; opaque at Google |
aud |
Your client_id |
The API |
| Purpose | Identify the user | Call an API within the granted scopes |
| Send to an API? | No | Yes, Authorization: Bearer |
The ID token tells your app "who showed up". The access token tells an API "what this app is allowed to do". Using one in place of the other is the root of most bugs here.
All of Google's endpoints are published in the discovery document, so there's no need to memorize them:
# Discovery document: endpoints, supported algorithms, claims
curl -s https://accounts.google.com/.well-known/openid-configuration \
| python3 -m json.tool | grep -E '"(issuer|authorization_endpoint|token_endpoint|jwks_uri)"'
Authorization Code + PKCE, step by step
For a web app with a server side, the right flow is Authorization Code with PKCE. The old Implicit flow (the token comes back directly in the URL fragment) is discouraged by RFC 9700, the OAuth 2.0 Security Best Current Practice.
Here's the flow:
- Preparation. The backend generates three random values:
state(CSRF protection),nonce(protection against ID token replay) andcode_verifier(the PKCE secret). All three go into the session. - Redirect to Google. The URL carries
client_id,redirect_uri,scope,state,nonceandcode_challenge = BASE64URL(SHA256(code_verifier)). The verifier itself never reaches the browser. - The user signs in at Google and consents. You never see the password, which is the main point of OIDC.
- Google sends the browser back to
redirect_uri?code=...&state=.... Thecodeis short-lived and single-use. It isn't a token yet. - The backend checks
stateand sends the code to the token endpoint over a server-to-server channel, together withclient_secretandcode_verifier. - Google compares
SHA256(code_verifier)with thecode_challengeit got earlier. If they match, it returnsaccess_token,id_token,expires_inandscope. - The backend verifies the ID token, finds or creates the user by
sub, and opens its own Django session.
Why PKCE when you already have a client_secret? The code travels through the browser: it can end up in server logs, proxies, browser history, or, on mobile, in the hands of another app. With PKCE an intercepted code is useless without the verifier. That's why RFC 9700 recommends PKCE for confidential clients too.
Code: login and callback in Django
The first view generates the PKCE pair and sends the user to Google.
# accounts/views.py
import base64
import hashlib
import secrets
from urllib.parse import urlencode
from django.conf import settings
from django.shortcuts import redirect
GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
def _pkce_pair() -> tuple[str, str]:
# 64 random bytes -> 86 URL-safe chars (RFC 7636 allows 43..128)
verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(verifier.encode("ascii")).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
return verifier, challenge
def google_login(request):
verifier, challenge = _pkce_pair()
state = secrets.token_urlsafe(32)
nonce = secrets.token_urlsafe(32)
request.session["oauth_google"] = {
"state": state,
"nonce": nonce,
"verifier": verifier,
}
params = {
"client_id": settings.GOOGLE_CLIENT_ID,
"redirect_uri": settings.GOOGLE_REDIRECT_URI, # exact match with Console
"response_type": "code",
"scope": "openid email profile",
"state": state,
"nonce": nonce,
"code_challenge": challenge,
"code_challenge_method": "S256",
}
return redirect(f"{GOOGLE_AUTH_URL}?{urlencode(params)}")
The callback checks state, exchanges the code and verifies the ID token. Popping the value out of the session matters: the code is single-use, so our state should be too.
# accounts/views.py (continued)
import requests
from django.contrib.auth import login
from django.http import HttpResponseBadRequest
from .google import InvalidIdToken, verify_google_id_token
from .services import AccountLinkRequired, get_or_create_user_from_google
GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"
def google_callback(request):
saved = request.session.pop("oauth_google", None)
if saved is None:
return HttpResponseBadRequest("No login in progress")
if "error" in request.GET: # e.g. access_denied
return HttpResponseBadRequest("Login cancelled")
state = request.GET.get("state", "")
if not secrets.compare_digest(state.encode(), saved["state"].encode()):
return HttpResponseBadRequest("Invalid state")
resp = requests.post(
GOOGLE_TOKEN_URL,
data={
"grant_type": "authorization_code",
"code": request.GET.get("code", ""),
"redirect_uri": settings.GOOGLE_REDIRECT_URI,
"client_id": settings.GOOGLE_CLIENT_ID,
"client_secret": settings.GOOGLE_CLIENT_SECRET,
"code_verifier": saved["verifier"],
},
timeout=10,
)
if resp.status_code != 200:
return HttpResponseBadRequest("Token exchange failed")
tokens = resp.json()
try:
claims = verify_google_id_token(tokens["id_token"], nonce=saved["nonce"])
user = get_or_create_user_from_google(claims)
except (KeyError, InvalidIdToken):
return HttpResponseBadRequest("Invalid ID token")
except AccountLinkRequired:
return redirect("/login/?link=google")
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
return redirect("/")
Notice that this is where our dealings with Google's tokens end. If all you need is login, there's no reason to store the access_token: you open your own session and you're done.
Verifying the ID token on the server
This is the most important part of the post. An ID token is a JWT of the form header.payload.signature. Reading the payload requires no key; it's just base64url. So "decode it and read the email" is not verification. Real verification has four parts:
- Signature. Google signs the token with its private key using RS256. The public keys are published as a JWK set at
jwks_uri, and the right one is picked by thekidin the header. Take the algorithm from your code, not from the token header. audmust equal yourclient_id. This is exactly what stops the "free quiz" attack.issishttps://accounts.google.comoraccounts.google.comfor Google.exp: the token must not be expired. Server clocks drift a little, so a few seconds ofleewayis standard practice.
On top of that, if you sent a nonce in the request, the nonce in the token must match the one in the session.
With PyJWT:
# accounts/google.py
import jwt
from django.conf import settings
GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs"
GOOGLE_ISSUERS = {"https://accounts.google.com", "accounts.google.com"}
# Module-level: the JWK set is cached between requests in this process
_jwks = jwt.PyJWKClient(GOOGLE_JWKS_URL, lifespan=3600, timeout=5)
class InvalidIdToken(Exception):
pass
def verify_google_id_token(token: str, nonce: str | None) -> dict:
try:
key = _jwks.get_signing_key_from_jwt(token) # picks key by "kid"
claims = jwt.decode(
token,
key.key,
algorithms=["RS256"], # never trust "alg" from the header
audience=settings.GOOGLE_CLIENT_ID,
options={"require": ["iss", "aud", "exp", "iat", "sub"]},
leeway=30, # small clock skew tolerance
)
except jwt.PyJWTError as exc:
raise InvalidIdToken(str(exc)) from exc
if claims["iss"] not in GOOGLE_ISSUERS:
raise InvalidIdToken("unexpected issuer")
if nonce is None or claims.get("nonce") != nonce:
raise InvalidIdToken("nonce mismatch")
return claims
PyJWKClient caches the JWK set and re-fetches it when a token carries an unknown kid. Google rotates its keys periodically, so hardcoding a public key is a login that will break suddenly one day.
If the project already uses the google-auth library, the same check is a single call:
from google.auth.transport import requests as google_requests
from google.oauth2 import id_token
# Checks signature, exp, aud and iss; raises ValueError on failure.
# The nonce still has to be compared by you.
claims = id_token.verify_oauth2_token(
token, google_requests.Request(), settings.GOOGLE_CLIENT_ID
)
Linking the user: sub, not email
The ID token contains email, email_verified, name, picture and, most importantly, sub. sub is a stable, unique identifier for the Google account. Email can change. So link by the (provider, sub) pair:
# accounts/models.py
from django.conf import settings
from django.db import models
class SocialAccount(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="social_accounts",
)
provider = models.CharField(max_length=32)
subject = models.CharField(max_length=255) # the "sub" claim
email = models.EmailField(blank=True) # informational only
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["provider", "subject"],
name="uniq_social_provider_subject",
),
]
# accounts/services.py
from django.contrib.auth import get_user_model
from django.db import IntegrityError, transaction
from .google import InvalidIdToken
from .models import SocialAccount
class AccountLinkRequired(Exception):
pass
def get_or_create_user_from_google(claims: dict):
sub = claims["sub"]
account = (
SocialAccount.objects.select_related("user")
.filter(provider="google", subject=sub)
.first()
)
if account is not None:
return account.user
if claims.get("email_verified") is not True:
raise InvalidIdToken("email is not verified")
User = get_user_model()
email = claims["email"].lower()
if User.objects.filter(email__iexact=email).exists():
# Someone already registered with this email (e.g. with a password).
# Make them log in first and link Google from settings.
raise AccountLinkRequired(email)
try:
with transaction.atomic():
user = User.objects.create_user(username=f"google_{sub}", email=email)
SocialAccount.objects.create(
user=user, provider="google", subject=sub, email=email
)
except IntegrityError:
# A parallel callback for the same Google account won the race
return SocialAccount.objects.get(provider="google", subject=sub).user
return user
Two decisions are baked in here. First, if email_verified isn't true, we don't trust the email. Second, if a user with that email already exists, we don't link the accounts automatically. Auto-linking is convenient, but the day you add a provider with weak email verification it turns into account takeover. The safe path: the user signs in with their existing method first, then connects Google from settings. The IntegrityError branch covers the callback being hit twice concurrently: the UniqueConstraint won't allow a duplicate.
Google Identity Services: the browser flow
Google's current JavaScript library is Google Identity Services (GIS). Its "Sign in with Google" button and One Tap prompt work without a redirect: the user picks an account and your callback receives response.credential. That credential is the ID token itself. Not an access token, and not a code.
<!-- templates/accounts/login.html -->
<script src="https://accounts.google.com/gsi/client" async></script>
<div id="google-btn"></div>
<script>
window.onload = () => {
google.accounts.id.initialize({
client_id: "{{ google_client_id }}",
nonce: "{{ gis_nonce }}",
callback: async (response) => {
const r = await fetch("/auth/google/gis/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": "{{ csrf_token }}",
},
body: JSON.stringify({ credential: response.credential }),
});
if (r.ok) window.location.href = "/";
},
});
google.accounts.id.renderButton(
document.getElementById("google-btn"),
{ theme: "outline", size: "large" },
);
};
</script>
The backend check is exactly the same: signature, aud, iss, exp, nonce. When the page is rendered, we put the nonce into the session and hand it to GIS:
# accounts/views.py (continued)
import json
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_POST
def login_page(request):
request.session["gis_nonce"] = secrets.token_urlsafe(32)
return render(request, "accounts/login.html", {
"google_client_id": settings.GOOGLE_CLIENT_ID,
"gis_nonce": request.session["gis_nonce"],
})
@require_POST
def google_gis(request):
nonce = request.session.pop("gis_nonce", None)
try:
credential = json.loads(request.body)["credential"]
claims = verify_google_id_token(credential, nonce=nonce)
user = get_or_create_user_from_google(claims)
except (ValueError, KeyError, TypeError, InvalidIdToken):
return JsonResponse({"error": "invalid_credential"}, status=400)
except AccountLinkRequired:
return JsonResponse({"error": "link_required"}, status=409)
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
return JsonResponse({"ok": True})
Django's CSRF protection stays in place: the fetch call sends the X-CSRFToken header. The GIS flow is for authentication. If you need to call Google APIs on the user's behalf, GIS handles that through its separate authorization part (google.accounts.oauth2), which leads you back to the Authorization Code flow.
Scopes: ask for less
openid email profile is enough for login. Extra scopes make the consent screen scary and hurt conversion. If you later need, say, calendar access, ask for it when the feature is actually used (incremental authorization; include_granted_scopes=true at Google). A refresh token is issued only with access_type=offline, and login doesn't need one.
One more nuance: the user can untick some permissions on the consent screen. The scope field in the token response shows what was actually granted, so check that the scope you need is there.
Mistakes that show up in production
audisn't checked. A token issued to another app works on yours. The most dangerous and most common mistake.- "Decoding" without a signature check.
jwt.decode(token, options={"verify_signature": False})is handy for debugging, but in production it accepts any forged token. - No
algorithmsargument. The algorithm must always be pinned by your code, never taken from the token header. - Email as the primary key. Email changes;
subdoesn't. email_verifiedignored. An unverified email is just a string.hdonly in the URL. If only users of your Workspace domain may sign in, adding thehdparameter to the request isn't enough; check thehdclaim in the token on the backend.- No
state. That opens the door to login CSRF: the attacker signs the victim into the attacker's account, and whatever the victim enters ends up with the attacker. redirect_urimismatch. Google requires an exact match:httpvshttps, the trailing/, the port all matter. Behind a reverse proxyrequest.build_absolute_uri()may returnhttp://, so take the URI from settings.SESSION_COOKIE_SAMESITE = "Strict". Returning from Google is a cross-site navigation, and Strict cookies aren't sent on it: the session is lost and you get "Invalid state" every time. Django's defaultLaxworks with this flow.- Reopening the callback. The code is single-use; a page refresh makes Google return
invalid_grant. Popping from the session turns that into a clean error. - Tokens in logs. Don't log
code,id_tokenoraccess_token, and don't pass them in URLs.
Practical checklist
- Authorization Code + PKCE (
S256), not the Implicit flow. - Fresh
state,nonce,code_verifierper login, stored in the session and used once. - ID token: signature (JWKS,
kid),algorithms=["RS256"],aud,iss,exp,nonce. - Users linked by
(provider, sub)with aUniqueConstraint. email_verifiedchecked; no auto-linking to existing accounts.redirect_uricomes from settings and matches the Console exactly.- Minimal scopes; extra permissions requested when needed.
- Your own session after login; Google tokens not stored unless you need them.
- No tokens in logs or URLs.
Takeaway
"Sign in with Google" is two protocols: OAuth 2.0 provides the code-for-tokens exchange, and OpenID Connect adds a signed ID token on top. Your backend must never take the client's word for it: a token whose signature, aud, iss, exp and nonce weren't checked is just a base64 string. Link users by sub, don't skip PKCE and state, and the login button stops being the weakest spot on your site.
// comments
Loading comments...