Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 77 ยท Authentication and Security

Social Login with OAuth (Google) and django-allauth

Add Sign in with Google to Django using django-allauth: how the OAuth 2.0 code flow works, how to get credentials, the settings you need, and a live run of the whole login.

"Sign in with Google" saves your users from inventing yet another password, and it saves you from storing and protecting one. The login itself happens on Google's site; your site only receives a short, verified statement: "this is the person with Google id 1098 and email [email protected]." The protocol behind this is OAuth 2.0 (with OpenID Connect on top for identity), and in Django the standard way to use it is the package django-allauth.

You should be comfortable with Users and Authentication and the custom user model lesson. Here you will first understand the flow, then run the real allauth code in the browser with the network calls to Google replaced by a small fake, so you can watch every step.

How the OAuth 2.0 authorization-code flow works

sequenceDiagram
    participant U as User's browser
    participant D as Your Django site
    participant G as Google
    U->>D: Click "Sign in with Google" (POST)
    D-->>U: Redirect to Google (client_id, redirect_uri, scope, state)
    U->>G: Log in and approve access
    G-->>U: Redirect back to /callback/?code=...&state=...
    U->>D: GET /callback/?code=...&state=...
    D->>G: POST code + client_secret to the token URL
    G-->>D: access token
    D->>G: GET user info with the access token
    G-->>D: id, email, name
    D-->>U: User is logged in (session cookie)

The browser carries only a one-time code. Your server exchanges it for a token over a private back-channel, using a secret that never reaches the browser.

Four ideas hold the flow together:

  • Client ID and secret identify your app to Google. The secret stays on the server.
  • Redirect URI is the exact URL Google may send the user back to. It must be registered in Google's console, which stops attackers from redirecting codes elsewhere.
  • Scope lists what you ask for (profile, email). Ask for the minimum.
  • State is a random value you generate before the redirect and check when the user returns. It defeats forged callbacks (a CSRF attack on the login itself).

Getting Google credentials

You do this once in the Google Cloud Console (the screens change, so follow Google's current documentation for names):

  1. Create a project and configure the OAuth consent screen (app name, support email).
  2. Create an OAuth client ID of type "Web application".
  3. Add Authorized redirect URIs: http://127.0.0.1:8000/accounts/google/login/callback/ for development and https://your-domain.com/accounts/google/login/callback/ for production.
  4. Copy the client ID and client secret into environment variables, not into the source code.

Installing and configuring allauth

Terminal
# read-only
pip install django-allauth
Python
# settings.py (read-only)
INSTALLED_APPS = [
    # ...the Django contrib apps...
    "django.contrib.sites",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
]

SITE_ID = 1

MIDDLEWARE = [
    # ...
    "allauth.account.middleware.AccountMiddleware",   # after AuthenticationMiddleware
]

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "APP": {
            "client_id": os.environ["GOOGLE_CLIENT_ID"],
            "secret": os.environ["GOOGLE_CLIENT_SECRET"],
        },
        "SCOPE": ["profile", "email"],
        "AUTH_PARAMS": {"access_type": "online"},
    }
}

LOGIN_REDIRECT_URL = "/"
Python
# urls.py (read-only)
urlpatterns = [
    path("accounts/", include("allauth.urls")),
]

Then python manage.py migrate creates allauth's tables (SocialAccount, SocialToken, EmailAddress). Credentials can alternatively live in the database as a SocialApp row added in the admin; the APP key in settings is simpler and keeps them in your deployment configuration.

In a template, a login button is a form that POSTs, not a link. A plain link (GET) would let any website start a login on a visitor's behalf:

HTML
<!-- read-only -->
{% load socialaccount %}
<form method="post" action="{% provider_login_url 'google' %}">
  {% csrf_token %}
  <button type="submit">Sign in with Google</button>
</form>

Running the whole flow

The example below uses the real allauth 65 with the Google provider. The only fake part is the network: requests.Session.request is replaced so that Google's token and user-info URLs return canned answers. Everything else (the redirect, the state check, the user and SocialAccount creation, the session login) is allauth's own code.

Python A complete Google login with django-allauth (Google replaced by a fake)

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.

Look at what allauth did for you. The user row was created automatically (the username ada is derived from the email), the Google identity is stored in SocialAccount (provider plus uid), and the second login reused them instead of creating duplicates. The forged callback with a wrong state never logged anybody in. This is the same code path a real site runs, with Google's servers behind it.

What to decide before going live

  • Email matching. If someone already registered with [email protected] and a password, then logs in with Google using the same address, allauth has to decide whether to connect them. Auto-connecting is only safe when the provider has verified the email; allauth's SOCIALACCOUNT_EMAIL_AUTHENTICATION and SOCIALACCOUNT_EMAIL_AUTHENTICATION_AUTO_CONNECT settings control this, and the defaults are cautious. Read them before enabling.
  • Signup flow. With SOCIALACCOUNT_AUTO_SIGNUP = True (the default) a complete profile creates the account immediately. Set it to False to show a form that asks for missing details such as a username.
  • A custom user model. allauth works with one; set ACCOUNT_USER_MODEL_USERNAME_FIELD = None when the model has no username.
  • Other providers. GitHub, Microsoft, Apple and dozens more follow the same pattern: add allauth.socialaccount.providers.<name> and a SOCIALACCOUNT_PROVIDERS entry.
  • HTTPS. Google only accepts non-HTTPS redirect URIs for localhost and 127.0.0.1. Production must use HTTPS and set SECURE_PROXY_SSL_HEADER correctly so the redirect URI Django builds matches the registered one. A mismatch gives Google's redirect_uri_mismatch error, the most common first problem.
  • Revoking. Users can disconnect from their account page (/accounts/social/connections/); decide what happens to an account that has no password left.

Never commit the client secret. If it leaks, rotate it in the Google console immediately. The client_id is public, the secret is not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the browser carry back from Google in the authorization-code flow?

    Only a short-lived code travels through the browser. Your server trades it for a token on a private back-channel, using the client secret.
  2. 2. What is the purpose of the state parameter?

    Your site stores state before redirecting and rejects a callback whose state does not match, which stops attackers from injecting their own authorization code.
  3. 3. Why is the 'Sign in with Google' button a POST form instead of a link?

    allauth requires a POST (with a CSRF token) by default so that a third-party page cannot start a login flow for a visitor.
  4. 4. Which value must NEVER be committed to a repository?

    The secret authenticates your server to Google. Keep it in an environment variable or secret store.

Summary

  • OAuth 2.0's authorization-code flow sends the browser to Google, receives a one-time code, and exchanges it server-side for a token and the user's profile.
  • Register exact redirect URIs, keep the client secret in the environment, and ask for the minimum scopes.
  • django-allauth adds the apps, middleware, URLs and SOCIALACCOUNT_PROVIDERS settings and handles the redirect, state check, token exchange, user creation and login.
  • Use a POST form for the login button, require HTTPS in production, and review the email-matching and auto-signup settings.

Next: Middleware.