Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 72 ยท Authentication and Security

Social Login with OAuth (Authlib)

Add "Sign in with Google" to Flask. Understand the OAuth 2 authorization code flow, the state parameter, token exchange and account linking, then wire it up with Authlib.

"Continue with Google" saves visitors from inventing yet another password, and saves you from storing and protecting it. The protocol behind these buttons is OAuth 2.0, and on top of it OpenID Connect (OIDC), which adds a standard way to learn who the user is. In Flask the usual library is Authlib.

Before you hide the flow behind a library, you should see it with your own eyes. In this lesson you will walk through the authorization code flow step by step with a small fake identity provider running right in the browser, learn the security checks that matter (state, redirect URIs, verified emails), solve account linking, and finally see the same login written with Authlib.

The cast and the flow

Three parties are involved: the user, your app (the client), and the identity provider (Google, GitHub, Microsoft, and so on). Your app never sees the user's password at the provider. It receives a short-lived authorization code, trades it for an access token on a server-to-server call, and uses the token to ask who the user is.

sequenceDiagram
    participant U as User's browser
    participant A as Your Flask app
    participant P as Identity provider
    U->>A: GET /login
    A-->>U: 302 to provider /authorize?client_id&redirect_uri&scope&state
    U->>P: user signs in and consents
    P-->>U: 302 to your /callback?code=...&state=...
    U->>A: GET /callback?code&state
    A->>A: check state matches the session
    A->>P: POST /token (code + client secret)
    P-->>A: access token
    A->>P: GET /userinfo (Bearer token)
    P-->>A: sub, email, email_verified, name
    A-->>U: set session, redirect home

The browser carries the code; only your server talks to the token endpoint, with the client secret.

Setting it up at a real provider means registering your app in their console (Google Cloud Console, GitHub Developer Settings) to get a client ID and client secret, and listing your exact redirect URI such as https://example.com/auth/callback. Keep the secret in environment variables, never in Git (Configuration).

Authlib's OIDC support loads the cryptography package, which cannot run in the browser editors of this site. So the runnable examples below implement the flow by hand with a fake provider, which is the best way to learn it anyway. The real Authlib code is shown read-only at the end.

The flow by hand

The example runs two Flask apps: a fake provider with /authorize, /token and /userinfo endpoints, and your app. The helper provider_post and provider_get stand in for HTTP calls; in production they would be requests.post(url, data=..., timeout=5) and requests.get(...). Follow the printed steps against the diagram above.

Python Authorization code flow with a fake provider

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.

Study the two attacks at the end: a forged callback and a replay of the finished one both fail, because the stored state is used up after one success. Without the state check, an attacker could trick a victim's browser into completing a login the attacker started, logging the victim in to the attacker's account (a login CSRF). The value is random, stored in the session before the redirect, compared when the browser returns, and thrown away. The provider also refuses to exchange the same code twice (our fake does this with CODES.pop), and refuses a redirect_uri that does not match the one used at the start.

Modern providers also support PKCE (a one-time code_verifier proven at the token call), required for apps that cannot keep a secret, and recommended for all clients. Authlib supports it with one option.

Account linking

After the callback you know the provider's stable identifier for the user, the sub claim ("subject"). Decide how it maps onto your users table. This is where real-world bugs and security holes appear:

  • Key identities by (provider, sub), never by email alone. Emails change and can be recycled.
  • A person who signed up with a password last year and now clicks "Continue with Google" with the same email should land in the same account, not a duplicate, but only if the provider vouches for the email (email_verified: true). Linking on an unverified email lets an attacker create an account at some provider with your victim's address and walk into the victim's account.
  • A user who is already logged in and connects a provider links it to the current account without guessing.
Python Find, link or create a local account

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.

In a real app these dictionaries are two tables: users and oauth_identities (provider, sub, user_id) with a unique constraint on (provider, sub). See Flask-SQLAlchemy Models and Flask-Login for logging the resolved user in with login_user.

Users who sign in only with a provider have no password. Make the password column nullable and offer "set a password" later, or hide the password form for them.

The same thing with Authlib

Authlib does all of the above (state, PKCE, token exchange, OIDC discovery, ID-token validation) from one registration. This is the read-only version you would use on a real server:

Python
import os
from authlib.integrations.flask_client import OAuth
from flask import Flask, redirect, session, url_for

app = Flask(__name__)
app.secret_key = os.environ["SECRET_KEY"]

oauth = OAuth(app)
oauth.register(
    name="google",
    client_id=os.environ["GOOGLE_CLIENT_ID"],
    client_secret=os.environ["GOOGLE_CLIENT_SECRET"],
    server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
    client_kwargs={"scope": "openid email profile"},
)


@app.get("/login")
def login():
    return oauth.google.authorize_redirect(url_for("callback", _external=True))


@app.get("/auth/callback")
def callback():
    token = oauth.google.authorize_access_token()     # checks state, exchanges the code, validates the ID token
    profile = token["userinfo"]                       # sub, email, email_verified, name, picture
    user_id, _how = login_with_provider("google", profile, session.get("user_id"))
    session["user_id"] = user_id
    return redirect("/")

server_metadata_url lets Authlib discover all the endpoints and signing keys, which is why you no longer list them by hand. login_with_provider is the function from the previous example. Register https://your-domain/auth/callback (and a http://localhost:5000/auth/callback entry for development) as an authorized redirect URI at the provider.

Checklist

  • Use the authorization code flow, with PKCE where offered. Do not use the old implicit flow.
  • Check state (Authlib does it for you) and register exact redirect URIs.
  • Link accounts only on a verified email, or when the user is already signed in.
  • Request the smallest scopes you need. openid email profile is enough for sign-in.
  • Store provider tokens only if you must call the provider's API later, and then encrypt them.
  • Offer more than one way to sign in, and a way to recover the account if a provider account is lost.
  • Treat a sign-in like any other: apply authorization checks afterwards, and keep session cookie flags strict.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does your server exchange at the provider's token endpoint?

    The browser only carries the short-lived code. Your server swaps it for an access token over a direct server-to-server call, using the client secret.
  2. 2. Why is the state parameter important?

    A random value saved in the session before redirecting and compared on return proves the callback belongs to this browser's own login attempt.
  3. 3. What should identify a social-login user in your database?

    The sub claim is the provider's stable id. Emails can change or be recycled, so they are not a safe primary key.
  4. 4. When is it safe to link a provider login to an existing local account automatically?

    Linking on an unverified email lets an attacker claim a victim's address at a provider and take over the victim's local account.

Summary

  • OAuth 2 / OIDC lets users sign in at a provider; your app receives a code, exchanges it for a token on the server side and reads the profile.
  • Always send and verify a random state; use exact redirect URIs, and PKCE where available.
  • Identify users by (provider, sub) and link by email only when email_verified is true or the user is already logged in.
  • Authlib's OAuth.register, authorize_redirect and authorize_access_token do the heavy lifting; the secrets belong in environment variables.
  • Plan for users without passwords and for account recovery.

Next: use what you know to ship a real project, starting with Deploying a Machine Learning Model with Flask.