Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 50 ยท Authentication and security

Google and social login (OAuth2 authorization code)

Add Sign in with Google (or GitHub) to FastAPI using the OAuth2 authorization code flow: redirect, state check, code exchange, user info, then your own session or JWT.

"Sign in with Google" saves users from inventing yet another password and saves you from storing one. Under the button sits a standard protocol, OAuth 2.0 with OpenID Connect. You never see the user's Google password: you send the browser to Google, Google authenticates the user, and then gives your server a short-lived one-time code that you swap for proof of who the user is.

This lesson explains each step, builds the whole flow in a form you can run here (with a stand-in identity provider so no real Google account or network is needed), and then shows the production version with the Authlib library. It assumes you know OAuth2 and JWT from the previous chapter.

Two different things called OAuth2

In OAuth2 and JWT your own API issued tokens to your own users (the password flow). Social login is different: another company is the identity provider, and your app is a client of it. The flow is called the authorization code flow, and it is the standard for web apps with a server.

The authorization code flow

Send the user away Redirect to Google with a state value.
User signs in Google asks, user agrees.
Google calls back Browser returns with ?code and state.
Swap the code Your server trades it for tokens.
1 / 2

One-time setup at the provider

For Google, you create an OAuth client in the Google Cloud console (APIs & Services, Credentials). You enter your authorized redirect URI, for example http://localhost:8000/auth/google/callback, and Google gives you a client id and a client secret. GitHub, Microsoft, Facebook and others work the same way. Two rules:

  • The client secret belongs only on your server, in an environment variable (see settings). Never ship it to a browser or a mobile app.
  • The redirect URI must match exactly what you registered. This is what stops attackers from receiving codes.

The flow, step by step

  1. /login: your endpoint generates a random state, stores it (in a cookie or the session) and redirects the browser to the provider's authorization URL with client_id, redirect_uri, response_type=code, scope (for Google: openid email profile) and state.
  2. The user signs in and approves.
  3. The provider redirects the browser to your callback: /auth/google/callback?code=...&state=....
  4. Check state. It must equal the value you stored. This defeats login-CSRF attacks, where an attacker tricks your user's browser into completing the attacker's login.
  5. Exchange the code: your server POSTs the code, the redirect URI, the client id and the secret to the provider's token endpoint and receives an access token (and an ID token).
  6. Get the profile: call the provider's userinfo endpoint with the access token (or read the ID token, which is a signed JWT).
  7. Create or find your user, keyed by the provider's stable sub (subject) id, not by email alone, then start your own session.

Step 5 happens server to server, so the code in the browser's address bar is useless to anyone who intercepts it without the client secret. That is the security point of this flow.

Run it: the whole flow with a stand-in provider

A real Google needs credentials and a public redirect, so here a second small FastAPI app plays "the identity provider" with the same three endpoints Google has (/authorize, /token, /userinfo). A tiny transport routes requests by host name so both apps talk in-process, and the "browser" is an httpx client that follows redirects and keeps cookies. The app itself is written the way a real one would be.

Python Authorization code flow, end to end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow the printed chain: your /login/google redirected to the provider's /authorize, which redirected back to your callback, which exchanged the code, created the user, set the session cookie and redirected to /me. A forged state is refused before any network call, and the code is accepted only once.

What this program simplified

  • The stand-in provider skipped the consent screen and ID token. A real provider also returns an ID token (a signed JWT) you can verify instead of calling /userinfo.
  • The state cookie and session signature use a hand-written HMAC, like in the JWT lesson: a teaching stand-in. Use real libraries.
  • The user table is a dictionary. In production, store provider, provider_user_id (sub) and email in a table with a unique constraint on provider plus id.
  • Cookies were not marked secure=True, which a real HTTPS site must set.

The production version with Authlib

Authlib handles state, PKCE, discovery and ID-token validation for you. Google publishes an OpenID Connect discovery document, so configuration is short. This code needs pip install authlib itsdangerous httpx and real credentials, so it is read-only.

Python
# Read-only: needs real Google credentials
from authlib.integrations.starlette_client import OAuth
from starlette.middleware.sessions import SessionMiddleware

app.add_middleware(SessionMiddleware, secret_key=settings.session_secret, https_only=True)

oauth = OAuth()
oauth.register(
    name="google",
    client_id=settings.google_client_id,
    client_secret=settings.google_client_secret,
    server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
    client_kwargs={"scope": "openid email profile"},
)

@app.get("/login/google")
async def login(request: Request):
    return await oauth.google.authorize_redirect(request, request.url_for("auth_google"))

@app.get("/auth/google/callback", name="auth_google")
async def auth_google(request: Request):
    token = await oauth.google.authorize_access_token(request)   # checks state, swaps the code
    info = token["userinfo"]                                     # from the verified ID token
    user = await get_or_create_user("google", info["sub"], info["email"], info["name"])
    request.session["uid"] = user.id
    return RedirectResponse("/")

SessionMiddleware stores the state (and later your uid) in a signed cookie. Authlib compares the state on the way back, exchanges the code and validates the ID token's signature, issuer, audience and expiry, which is the hardest part to get right by hand.

Session or JWT after login?

After Google says "this is user 1048", your app must remember it. Two common answers:

  • A server-side session cookie (as above): simplest and best for a website served from the same site. The cookie is HttpOnly, so scripts cannot read it.
  • Your own JWT returned to a single-page or mobile app. Redirect the browser to the front end with a short-lived one-time code, or set the token in an HttpOnly cookie. Avoid putting tokens into URLs, which end up in logs and history.

With a React front end

A common arrangement is a React app on app.example.com and the API on api.example.com. The React app simply navigates (a full page load, not fetch) to https://api.example.com/login/google. After the callback, the API sets an HttpOnly session cookie and redirects to https://app.example.com/. React then calls GET /me with fetch(url, { credentials: "include" }) to learn who is signed in. For that to work you need CORS with allow_credentials=True and the exact front-end origin (never *), as covered in Middleware and CORS, and cookies with SameSite and Domain settings that allow the two subdomains.

Security checklist

  • Always verify state; use PKCE as well for public clients (Authlib adds it for you when configured).
  • Match accounts by the provider's sub, and only trust email when email_verified is true; otherwise someone can claim another person's address.
  • Keep the client secret in the environment. Rotate it if it leaks.
  • Exact redirect URIs only, HTTPS in production, secure and HttpOnly cookies.
  • Request the smallest scope you need. openid email profile is enough for sign-in.
  • Offer another way in (or account recovery) if you cannot afford to lose access when a provider account is lost.
  • Treat tokens like passwords: never log them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the authorization code flow, what does the browser carry back to your callback URL?

    The redirect carries code and state. Your server then exchanges the code for tokens, using the secret the browser never sees.
  2. 2. What attack does checking the state parameter prevent?

    State ties the callback to the login attempt your server started. A forged callback will not match the stored value.
  3. 3. Why should the code exchange happen on your server and not in browser JavaScript?

    The token request includes the client secret. Putting it in front-end code would leak it.
  4. 4. How should you identify a returning Google user in your database?

    sub never changes for a user. Emails and names can change, and access tokens expire.

Summary

  • Social login uses the OAuth2 authorization code flow: redirect with state, receive code, exchange it server to server, fetch the profile, then start your own session.
  • Register your redirect URI at the provider; keep the client secret on the server only.
  • Verify state, match users by sub, trust email only when verified, and use HTTPS with HttpOnly cookies.
  • Authlib implements the flow, PKCE and ID-token validation for production; the in-browser example used a stand-in provider to show every step.
  • After login, a session cookie suits websites; a React front end can call /me with credentials: "include" and CORS configured for credentials.

Next: protect individual endpoints with Permissions and scopes if you have not already, or move on to API keys and security practices.