Python

Implementing OAuth2 with Google & GitHub Social Login in FastAPI

Social login has become a common feature in modern web applications. Instead of asking users to create another password, we can let them sign in using an…

D
DevByteTechnical Author
Published
10 min read2 views
Implementing OAuth2 with Google & GitHub Social Login in FastAPI

Social login has become a common feature in modern web applications. Instead of asking users to create another password, we can let them sign in using an account they already have, such as Google or GitHub.

For developers, this means less password-management complexity and a smoother onboarding experience. But implementing social login correctly involves more than redirecting users to a provider and receiving an email address. We need to handle OAuth authorization, validate the callback, identify the user, manage application sessions, and protect sensitive tokens.

In this guide, we’ll build a practical Google and GitHub social login flow using FastAPI.

We’ll cover:

  • How OAuth2 authorization code flow works

  • Creating Google and GitHub OAuth applications

  • Configuring FastAPI

  • Implementing login and callback routes

  • Finding or creating users in a database

  • Issuing our own application token

  • Handling common security and production concerns

The examples use FastAPI with Authlib and a JWT-based application token. The same approach can be adapted to PostgreSQL, MySQL, or MongoDB.

1. Understanding the OAuth2 Authorization Code Flow

OAuth2 allows an application to obtain authorization through another service. In social login, the provider also gives us identity information through an authenticated user-info endpoint or an identity token.

The high-level flow looks like this:

  1. The user clicks “Continue with Google” or “Continue with GitHub.”

  2. FastAPI redirects the user to the provider’s authorization page.

  3. The user signs in and approves the requested permissions.

  4. The provider redirects the user back to our callback URL with an authorization code.

  5. FastAPI exchanges that code for an access token.

  6. FastAPI fetches the user’s profile.

  7. Our application finds or creates the local user.

  8. FastAPI creates an application session or JWT and redirects the user to the frontend.

The provider’s access token and our application token serve different purposes.

The provider token lets our backend call the provider’s APIs. Our application token identifies the user inside our own system. We should not treat these tokens as interchangeable.

2. Install the Required Packages

Create a FastAPI project and install the required dependencies:

pip install fastapi uvicorn authlib httpx python-jose[cryptography] python-dotenv

We’ll use:

  • fastapi to create the API

  • authlib to handle OAuth client operations

  • httpx for asynchronous HTTP requests

  • python-jose to create JWTs

  • python-dotenv to load environment variables

For a production application, use a persistent database and a migration tool such as Alembic if you are working with SQLAlchemy.

3. Create Google OAuth Credentials

Open the Google Cloud Console and create or select a project.

Configure the OAuth consent screen, then create an OAuth client ID for a web application.

Add your callback URL to the authorized redirect URIs:

http://localhost:8000/auth/google/callback

For production, use your HTTPS domain:

https://api.example.com/auth/google/callback

Google requires the callback URL to match the configured redirect URI.

You’ll receive a client ID and client secret. Keep the secret on the backend and never expose it in frontend code.

4. Create GitHub OAuth Credentials

Open GitHub Developer Settings and create a new OAuth App.

Set the authorization callback URL to:

http://localhost:8000/auth/github/callback

For production, configure the corresponding HTTPS callback.

GitHub provides a client ID and client secret. Store them securely, just like the Google credentials.

5. Configure Environment Variables

Create a .env file:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret

JWT_SECRET=replace-with-a-long-random-secret
FRONTEND_URL=http://localhost:3000

Add .env to .gitignore:

.env

Do not commit client secrets or JWT signing keys to your repository. In production, use a secrets manager or your hosting provider’s secret configuration.

6. Create the FastAPI Application

Create a file named main.py.

We’ll configure both OAuth providers through Authlib. The routes will redirect the user to the provider and process the callback.

import os
from datetime import datetime, timedelta, timezone

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from authlib.integrations.starlette_client import OAuth
from jose import jwt

load_dotenv()

app = FastAPI()

oauth = OAuth()

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

oauth.register(
    name="github",
    client_id=os.getenv("GITHUB_CLIENT_ID"),
    client_secret=os.getenv("GITHUB_CLIENT_SECRET"),
    authorize_url="https://github.com/login/oauth/authorize",
    access_token_url="https://github.com/login/oauth/access_token",
    api_base_url="https://api.github.com/",
    client_kwargs={
        "scope": "read:user user:email",
    },
)

Google uses OpenID Connect, so the openid email profile scopes request identity information.

GitHub’s OAuth App flow uses scopes such as read:user and user:email. We’ll fetch the user profile and, if needed, their email information through GitHub’s API.

7. Create a Function to Generate an Application JWT

After the user authenticates with Google or GitHub, our application needs its own way to authenticate subsequent requests.

For this example, we’ll create a JWT:

JWT_SECRET = os.getenv("JWT_SECRET")
JWT_ALGORITHM = "HS256"


def create_access_token(user_id: str) -> str:
    expires_at = datetime.now(timezone.utc) + timedelta(minutes=30)

    payload = {
        "sub": user_id,
        "exp": expires_at,
    }

    return jwt.encode(
        payload,
        JWT_SECRET,
        algorithm=JWT_ALGORITHM,
    )

The sub claim identifies the user. The exp claim defines when the token expires.

In production, validate that the signing secret is configured and sufficiently random. Depending on your application, you may also want refresh-token rotation, token revocation, and session tracking.

8. Add a User Lookup or Creation Function

Social login should connect a provider account to a local application user.

A simplified example might look like this:

async def get_or_create_user(
    provider: str,
    provider_user_id: str,
    email: str | None,
    name: str | None,
):
    # Replace this with a real database operation.
    #
    # 1. Look up a user by provider + provider_user_id.
    # 2. If found, update profile information if appropriate.
    # 3. If not found, create a new user.
    # 4. Return the local user record.

    return {
        "id": f"{provider}:{provider_user_id}",
        "email": email,
        "name": name,
        "provider": provider,
    }

This is only a placeholder. A real database should enforce a unique constraint on the provider and provider-user-ID pair.

Avoid relying only on an email address to identify the social account. Email addresses can be missing, private, or changed. The provider’s stable user ID is the more reliable identifier.

9. Implement Google Login

First, create the login route:

@app.get("/auth/google/login")
async def google_login(request: Request):
    redirect_uri = request.url_for("google_callback")

    return await oauth.google.authorize_redirect(
        request,
        redirect_uri,
    )

When a user visits /auth/google/login, FastAPI redirects them to Google’s authorization page.

Now implement the callback:

@app.get("/auth/google/callback", name="google_callback")
async def google_callback(request: Request):
    token = await oauth.google.authorize_access_token(request)

    user_info = token.get("userinfo")

    if not user_info:
        raise HTTPException(
            status_code=400,
            detail="Unable to retrieve Google user information",
        )

    provider_user_id = user_info.get("sub")
    email = user_info.get("email")
    name = user_info.get("name")

    if not provider_user_id:
        raise HTTPException(
            status_code=400,
            detail="Google account ID is missing",
        )

    user = await get_or_create_user(
        provider="google",
        provider_user_id=provider_user_id,
        email=email,
        name=name,
    )

    access_token = create_access_token(str(user["id"]))

    frontend_url = os.getenv("FRONTEND_URL")

    response = RedirectResponse(
        url=f"{frontend_url}/auth/callback",
        status_code=302,
    )

    response.set_cookie(
        key="access_token",
        value=access_token,
        httponly=True,
        secure=False,  # Set True in production with HTTPS.
        samesite="lax",
        max_age=1800,
    )

    return response

Authlib uses the OAuth state parameter to protect the authorization flow against cross-site request forgery. The callback exchanges the authorization code and obtains the user information.

The example places the application JWT in an HTTP-only cookie. JavaScript cannot read an HTTP-only cookie, which helps reduce the risk of token theft through certain client-side attacks.

For local development, secure=False allows the cookie to work over HTTP. In production, use HTTPS and set secure=True.

10. Implement GitHub Login

GitHub’s flow is similar, but we fetch the profile using GitHub’s API.

Create the login route:

@app.get("/auth/github/login")
async def github_login(request: Request):
    redirect_uri = request.url_for("github_callback")

    return await oauth.github.authorize_redirect(
        request,
        redirect_uri,
    )

Now add the callback:

@app.get("/auth/github/callback", name="github_callback")
async def github_callback(request: Request):
    token = await oauth.github.authorize_access_token(request)

    response = await oauth.github.get(
        "user",
        token=token,
    )

    profile = response.json()

    provider_user_id = profile.get("id")
    name = profile.get("name") or profile.get("login")
    email = profile.get("email")

    if not provider_user_id:
        raise HTTPException(
            status_code=400,
            detail="GitHub account ID is missing",
        )

    if not email:
        email_response = await oauth.github.get(
            "user/emails",
            token=token,
        )

        emails = email_response.json()

        primary_verified_email = next(
            (
                item["email"]
                for item in emails
                if item.get("primary") and item.get("verified")
            ),
            None,
        )

        email = primary_verified_email

    user = await get_or_create_user(
        provider="github",
        provider_user_id=str(provider_user_id),
        email=email,
        name=name,
    )

    access_token = create_access_token(str(user["id"]))

    frontend_url = os.getenv("FRONTEND_URL")

    response = RedirectResponse(
        url=f"{frontend_url}/auth/callback",
        status_code=302,
    )

    response.set_cookie(
        key="access_token",
        value=access_token,
        httponly=True,
        secure=False,  # Set True in production with HTTPS.
        samesite="lax",
        max_age=1800,
    )

    return response

GitHub may not expose the user’s email in the profile endpoint. If the email is private, the application can request user:email and query /user/emails.

We select only a primary, verified email address. If no verified email is available, the application should decide whether to allow an account without an email or ask the user to provide one.

11. Protect an API Route

Once the application has issued its own token, we can validate it when users access protected routes.

For a simple bearer-token example:

from fastapi import Depends
from fastapi.security import HTTPAuthorizationCredentials
from fastapi.security import HTTPBearer

bearer_scheme = HTTPBearer()


def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
):
    token = credentials.credentials

    try:
        payload = jwt.decode(
            token,
            JWT_SECRET,
            algorithms=[JWT_ALGORITHM],
        )
    except Exception:
        raise HTTPException(
            status_code=401,
            detail="Invalid or expired token",
        )

    user_id = payload.get("sub")

    if not user_id:
        raise HTTPException(
            status_code=401,
            detail="Invalid token payload",
        )

    return {"id": user_id}


@app.get("/users/me")
async def get_me(user=Depends(get_current_user)):
    return user

This example uses the Authorization: Bearer header. If the application stores its JWT in an HTTP-only cookie, the dependency should instead read and validate the cookie.

Do not accept a token from an untrusted source without validating its signature, expiration, and expected claims.

12. Frontend Integration

For a React or Next.js frontend, social login can be implemented using simple links or buttons.

const API_URL = "http://localhost:8000";

export default function SocialLogin() {
  return (
    <div>
      <a href={`${API_URL}/auth/google/login`}>
        Continue with Google
      </a>

      <a href={`${API_URL}/auth/github/login`}>
        Continue with GitHub
      </a>
    </div>
  );
}

The browser navigates to FastAPI, which handles the OAuth redirect.

If the backend and frontend are on different origins and you use cookies, configure CORS carefully:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "OPTIONS"],
    allow_headers=["Content-Type", "Authorization"],
)

When credentials are enabled, do not use a wildcard origin. Specify the frontend origins you trust.

For cross-site cookies, you may need SameSite=None; Secure, which requires HTTPS. Also consider CSRF protection for state-changing requests authenticated through cookies.

13. Production Security Checklist

A working social login flow is only the starting point. Before deploying it, review the following:

Use HTTPS

All production callback URLs should use HTTPS. Set secure cookies and avoid sending tokens over unencrypted connections.

Keep provider secrets private

Store Google and GitHub client secrets in environment variables or a secrets manager. Never place them in frontend code or commit them to Git.

Use stable provider identifiers

Store the provider name and provider user ID. Do not use email alone as the account identity.

A typical database table might include:

users
-----
id
name
email
created_at

social_accounts
---------------
id
user_id
provider
provider_user_id
created_at

Add a unique constraint to (provider, provider_user_id).

Handle account linking carefully

If a user signs in with Google and later uses GitHub with the same email, do not automatically merge the accounts unless your account-linking policy verifies that this is safe.

A safer flow asks the user to authenticate to the existing account before linking another provider.

Validate email verification

If your application relies on email ownership, verify that the provider confirms the email is verified. Treat missing or unverified emails appropriately.

Avoid exposing provider tokens

Do not send Google or GitHub access tokens to the frontend unless there is a clear requirement. Keep provider tokens on the backend and request only the scopes your application needs.

Use proper session management

A short-lived JWT can work for simple applications. For more advanced systems, consider server-side sessions or refresh-token rotation with revocation support.

Add logging without leaking secrets

Log authentication failures and useful diagnostic information, but never log authorization codes, access tokens, refresh tokens, or client secrets.

14. Common OAuth2 Errors

Error

Possible reason

What to check

redirect_uri_mismatch

Callback URL differs from provider configuration

Verify the exact scheme, host, path, and port

invalid_client

Client ID or secret is incorrect

Check environment variables

Missing GitHub email

Email is private

Request user:email and call /user/emails

State mismatch

OAuth state validation failed

Check session and cookie configuration

Cookie not stored

Cookie attributes conflict with deployment

Review Secure, SameSite, domain, and HTTPS

Frontend CORS error

Frontend origin is not allowed

Configure explicit origins and credentials

OAuth errors often come from configuration differences between local and production environments. Keep callback URLs and provider credentials environment-specific.

15. Run the Application

Start FastAPI:

uvicorn main:app --reload

Open:

http://localhost:8000/docs

You can test the login routes directly in your browser:

http://localhost:8000/auth/google/login
http://localhost:8000/auth/github/login

The browser will redirect to the provider and return to the configured callback after authentication.

Conclusion

Implementing Google and GitHub social login in FastAPI is straightforward once we understand the OAuth2 authorization code flow. Authlib handles much of the OAuth client work, while FastAPI gives us a clean way to build login routes, callback handlers, and protected APIs.

The important part is not simply getting a user’s profile. A production-ready implementation must also handle stable provider IDs, verified emails, secure application sessions, cookie configuration, account linking, and secret management.

Start with a simple flow, then add database persistence, session revocation, and account-linking features as your application grows.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘