Mann Limbachiya

All writing

Security engineering · Authentication

What actually happens when you click “Sign in with Google”?

One click sets off browser redirects, authorization requests, cryptographic challenges, a token exchange, JWT signature verification, user provisioning, and session management. Your application never sees the user's Google password. Here is the whole path, from the login button to a protected API.

Mann Limbachiya··15 min read
Hand-drawn sketch of a person asking “What is OIDC Flow?” next to a browser, frontend, backend, and identity provider all pointing at a shared question mark
Four systems, one question mark. The flow is really a conversation about who the user is, and which system is allowed to say so.

You click Sign in with Google. A login screen appears. You pick an account, enter your credentials, approve the requested permissions, and suddenly you are inside the application.

It feels like a simple operation. Behind that single click, several things happen: browser redirects, authorization requests, cryptographic challenges, token exchanges, JWT signature verification, user provisioning, and session management.

And here is the interesting part: your application never needs to see the user's Google password. That is one of the fundamental ideas behind OpenID Connect.

I wanted to break down what actually happens behind this experience, from the first click on Sign Up to accessing a protected backend API. Let's walk through it as if we are building an application with React, FastAPI, and Google as the Identity Provider.

Section 01

What exactly is OpenID Connect?

OpenID Connect is an identity layer built on top of OAuth 2.0. To understand why it exists, we need to distinguish authentication from authorization.

Authentication

Who are you? Establishing and verifying the identity of the person or system making a request.

Authorization

What are you allowed to access? Deciding which resources and actions that identity is permitted to use.

OAuth 2.0 primarily deals with delegated authorization. OIDC adds a standardized way for applications to authenticate users and obtain information about their identity.

For example, when you use Google to sign in to another application:

  1. Google authenticates you.
  2. Google provides your application with an identity assertion.
  3. Your application verifies that assertion.
  4. Your application identifies or creates a corresponding user account.

Your application trusts Google to authenticate the user, rather than implementing its own Google password verification mechanism.

1.1The main components

Before getting into the flow, let's identify the systems involved.

ComponentResponsibility
User / BrowserInitiates authentication and interacts with the application
FrontendReact or Angular application
BackendFastAPI application handling authentication and business APIs
Identity Provider (IdP)Google, Okta, ForgeRock, or Keycloak
Application DatabaseStores application-specific user information
Session StoreMaintains authenticated application sessions

One important distinction: Google authenticates the user, but your application remains responsible for managing its own user accounts, roles, permissions, and business data.

Section 02

Before the first login: what needs to be configured?

You cannot simply add a Google login button to your frontend and expect OIDC authentication to work. First, you need to establish trust between your application and the Identity Provider.

Step 1Register your application with the Identity Provider

Suppose we are using Google. We register our application through Google Cloud Console and configure:

  • Application name
  • Application type
  • Authorized redirect URI
  • Authorized JavaScript origins, where applicable

Once registered, Google provides a Client ID and, for a confidential web client, a Client Secret.

Client ID

Identifies your application to Google. It is not a secret and is safe to include in authorization requests.

Client Secret

Authenticates a confidential client during the token exchange. It must stay on the backend and should never be exposed in frontend JavaScript.

A browser-only SPA is a public client and must not rely on a client secret. It should use Authorization Code Flow with PKCE.

Step 2Configure the redirect URI

Imagine our application is running at:

Application origin
https://app.example.com

After successful authentication, Google needs to know where to send the browser. We register:

Registered redirect URI
https://app.example.com/auth/callback

The URI used in the authorization request must match the registered URI. If it doesn't, the Identity Provider rejects the authentication request.

Step 3Configure OIDC scopes

Scopes define the identity information and permissions being requested. For basic authentication, we generally use:

ScopePurpose
openidIdentifies the request as an OIDC authentication request
profileRequests profile information
emailRequests email-related claims

The openid scope is particularly important. Without it, the request is an OAuth authorization request, not a standard OIDC authentication request.

Step 4Configure OIDC endpoints

Your application needs to know where to send authentication requests and exchange authorization codes. Most OIDC providers expose a discovery document. For Google:

OIDC discovery document
https://accounts.google.com/.well-known/openid-configuration

This document provides metadata such as:

  • Authorization endpoint
  • Token endpoint
  • UserInfo endpoint
  • JWKS URI
  • Supported scopes
  • Supported signing algorithms

Using OIDC Discovery makes integration easier because your application doesn't need to hardcode every endpoint.

Step 5Configure security mechanisms

For a modern web application, Authorization Code Flow with PKCE is a good default. You should also configure:

  • State: protects against CSRF and correlates the authentication transaction.
  • Nonce: binds the ID token to the original authentication request.
  • PKCE: protects the authorization code exchange.
  • HTTPS: protects communication.
  • Secure session management.
  • Exact redirect URI validation.

Now the application and Identity Provider are configured to communicate. Let's see what happens when an actual user clicks Sign Up.

Section 03

The complete OIDC authentication flow

We will use Authorization Code Flow with PKCE and a Backend-for-Frontend (BFF) architecture. Our stack:

Frontend: React
Backend: FastAPI
Identity Provider: Google
Database: PostgreSQL
Session Store: Redis

The sequence diagram below shows every hop: the login request, the generated security values, the redirect to Google, the callback, the token exchange, JWKS retrieval, ID token validation, user provisioning, session creation, and the protected API call.

Sequence diagram of the full OIDC flow between the user, React frontend, FastAPI backend, Google or ForgeRock identity provider, and the application database, numbered from clicking Sign Up to displaying transactions
The full authorization code flow with PKCE and a backend-for-frontend. Steps 12 through 26 are the part most login buttons hide.

Step 1User clicks Sign Up

The user opens our application and clicks Sign Up. The frontend initiates authentication by calling GET /auth/login. The backend prepares the OIDC authentication transaction.

It generates three important values:

  • State — a random value used to correlate the authentication request and response.
  • Nonce — a random value that will later be checked against the ID token.
  • Code Verifier — a cryptographically random secret used in PKCE.
PKCE values
code_verifier  = dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

code_challenge = BASE64URL(SHA256(code_verifier))

The code verifier stays securely associated with the authentication transaction. The code challenge is sent to the Identity Provider.

Why do we need this? Imagine an attacker intercepts the authorization code during the redirect back to your application. Without the original code verifier, the attacker cannot successfully redeem the code when PKCE is enforced. That is the protection PKCE provides.

Step 2Redirect the browser to Google

The backend constructs the authorization request and redirects the browser to Google's authorization endpoint. An illustrative request looks like this:

Authorization request
GET https://accounts.google.com/o/oauth2/v2/auth
  ?client_id=YOUR_CLIENT_ID
  &redirect_uri=https://app.example.com/auth/callback
  &response_type=code
  &scope=openid profile email
  &state=RANDOM_STATE
  &nonce=RANDOM_NONCE
  &code_challenge=GENERATED_CHALLENGE
  &code_challenge_method=S256
ParameterPurpose
client_idIdentifies the application
redirect_uriWhere the browser returns after authentication
response_type=codeRequests an authorization code
scopeSpecifies requested identity information
stateCorrelates the authentication transaction
nonceBinds the resulting ID token to the request
code_challengePKCE challenge
code_challenge_methodSpecifies the challenge algorithm

Notice that we are not directly sending the user to Google's homepage. We are sending the browser to a specific authorization endpoint with a structured authentication request.

Step 3Google authenticates the user

Google displays its login interface. The user might:

  1. Select an existing Google account.
  2. Enter their email address.
  3. Enter their password.
  4. Complete MFA if required.
  5. Approve the requested permissions if consent is required.

Google validates the credentials and establishes its own authenticated browser session. Here is an important detail: your FastAPI backend never receives the Google password. Google handles authentication within its own environment.

If the user is already authenticated with Google, the provider may recognise its existing browser session and skip some login steps.

Step 4Google redirects the browser back

After successful authentication and any required consent, Google redirects the browser to the registered callback URI. For example:

Callback
https://app.example.com/auth/callback
  ?code=AUTHORIZATION_CODE
  &state=RANDOM_STATE

Two important values are returned: the authorization code and the state.

The authorization code is temporary and can only be redeemed under the appropriate client, redirect URI, and PKCE conditions. The application checks that the returned state matches the value stored for the original authentication transaction. If it doesn't match, reject the response.

Why doesn't Google directly return the ID token here? Because we are using Authorization Code Flow. The authorization code must first be exchanged at the token endpoint.

Step 5Backend exchanges the authorization code for tokens

Now our backend has the authorization code. It sends a POST request to Google's token endpoint.

Token request
POST https://oauth2.googleapis.com/token

grant_type=authorization_code
code=AUTHORIZATION_CODE
redirect_uri=https://app.example.com/auth/callback
client_id=YOUR_CLIENT_ID
code_verifier=ORIGINAL_CODE_VERIFIER

For a confidential client, the backend also authenticates using its configured client authentication method, such as a client secret.

Google validates:

  • Authorization code
  • Client identity
  • Redirect URI
  • Code verifier
  • Code expiration and usage status

If everything is valid, Google returns tokens. An illustrative response:

Token response
{
  "access_token": "ACCESS_TOKEN",
  "expires_in": 3600,
  "token_type": "Bearer",
  "id_token": "JWT_ID_TOKEN",
  "refresh_token": "REFRESH_TOKEN"
}

A refresh token isn't necessarily returned on every authentication.

Section 04

Understand the three tokens

Before validating anything, it helps to be precise about what each token is for.

ID Token

Tells your OIDC client who authenticated. A signed JWT containing identity claims.

Access Token

Used to access protected resources. It may be used to call a resource server when the token is intended for that API.

Refresh Token

Used to obtain a new access token when the current one expires, subject to the provider's policies.

The important distinction:

  • ID Token = Authentication
  • Access Token = Authorization
  • Refresh Token = Token renewal

Don't treat them as interchangeable.

The payloadWhat an ID token actually contains

Illustrative ID token payload
{
  "iss": "https://accounts.google.com",
  "sub": "109876543210",
  "aud": "YOUR_CLIENT_ID",
  "email": "[email protected]",
  "email_verified": true,
  "name": "John",
  "nonce": "ORIGINAL_NONCE",
  "exp": 1790000000
}

That payload is illustrative. The values come from the Identity Provider and are only trustworthy after the signature and claims have been verified.

Section 05

Backend validates the ID token

This is one of the most important security steps. Receiving a JWT doesn't automatically mean you can trust it. An ID token generally follows this structure:

JWT structure
HEADER.PAYLOAD.SIGNATURE

Your backend must verify its signature and claims. First, it reads the JWT header.

Decoded JWT header
{
  "alg": "RS256",
  "kid": "abc123"
}

The kid identifies which signing key was used. Next, your backend retrieves the Identity Provider's public keys from its JWKS endpoint. JWKS stands for JSON Web Key Set.

The backend selects the key matching the JWT's kid and verifies the signature. Why does this work? The Identity Provider signs the token using its private signing key. Your backend verifies that signature using the corresponding public key. The private signing key is never shared with your application.

But signature verification alone isn't sufficient. Your backend must also validate the relevant claims:

ClaimValidation
issExpected token issuer
audIntended client application
expToken hasn’t expired
iatIssuance time is acceptable
nonceMatches the original authentication request
subValid subject identifier

Depending on the token and client configuration, additional claims such as azp may also need validation.

Never simply Base64-decode a JWT and trust the payload. Decoding isn't verification.

Section 06

Find or create the application user

Now that the ID token has been verified, our backend knows which identity has authenticated. But does this user already exist in our application?

We query PostgreSQL using the issuer and subject combination. For example:

Look up the external identity
SELECT *
FROM users
WHERE provider_issuer = 'https://accounts.google.com'
AND provider_subject = '109876543210';

Two scenarios are possible.

Scenario A: New user

No matching account exists. Our backend creates an application user and assigns the appropriate default role and onboarding status.

Scenario B: Existing user

The matching account exists. Our backend retrieves the existing application user.

A crucial implementation detail: use the combination of iss and sub as the stable external identity key. Don't automatically link accounts just because their email addresses match.

Google authenticates the identity. Your application manages the account.

Section 07

Create the application session

After identifying the user, the backend creates an application session. For a BFF architecture, the browser receives a secure session cookie.

Session cookie
Set-Cookie: session_id=RANDOM_SESSION_ID;
            HttpOnly;
            Secure;
            SameSite=Lax;
            Path=/

The session identifier is associated with a server-side session record. The frontend doesn't need to access the Google ID token, refresh token, or client secret. The backend can now redirect the user to https://app.example.com/dashboard. The user is successfully authenticated.

Section 08

What happens when the user accesses a protected API?

Let's say the dashboard has a View Transactions button. The frontend calls:

Protected API request
GET /api/transactions

In our BFF architecture, the browser sends the session cookie automatically when the cookie's scope and security settings permit it. The backend:

  1. Validates the session.
  2. Identifies the authenticated user.
  3. Checks the user's permissions.
  4. Fetches the relevant transactions.
  5. Returns the API response.

This is where authentication and authorization become separate responsibilities. A user can be successfully authenticated but still not have permission to perform a particular operation. For example, a normal user might view transactions but not delete them.

If you use a direct SPA-to-API bearer-token architecture instead, the browser sends an access token in the Authorization header, and the resource server validates that access token.

Section 09

BFF vs SPA: which architecture should you use?

There are two common approaches to integrating OIDC into a web application.

ResponsibilityBFFSPA
PKCE generationBackendFrontend
Callback handlingBackendFrontend
Code exchangeBackendFrontend
Client secretBackend, if applicableNot used
Token exposure to JavaScriptAvoidedTokens may be accessible depending on storage
Application sessionServer-side sessionUsually client-managed token/session approach

For a traditional web application, I generally prefer the Backend-for-Frontend pattern. It keeps provider tokens and sensitive credentials away from browser JavaScript and makes application session management more straightforward.

A SPA can also securely use Authorization Code Flow with PKCE, but token storage and browser security need careful consideration.

Section 10

What about logout?

Logout is another important part of the authentication lifecycle. When the user clicks Logout, your backend should:

  1. Invalidate the application session.
  2. Clear the session cookie.
  3. Redirect the user to the login page.

But here is something worth remembering.

Logging out of your application doesn't necessarily log the user out of Google. Google may still maintain its own browser session.

OIDC also defines RP-Initiated Logout, which allows an application to initiate logout at the Identity Provider when supported. These are separate sessions and should be treated accordingly.

Section 11

Common OIDC implementation mistakes

While implementing OIDC, these are some things I would pay particular attention to.

MistakeWhy it matters
Skipping state validationCreates CSRF and response-injection risks
Not validating nonceWeakens ID token request binding
Exposing client secret in frontendCompromises confidential client credentials
Not using PKCELeaves authorization-code exchange more vulnerable to interception
Trusting a decoded JWTDoesn’t establish signature authenticity
Checking email alone for identityCan cause incorrect account linking
Using ID token as API access tokenConfuses authentication with authorization
Ignoring session securityCan expose authenticated sessions
Not validating audienceMay accept a token intended for another client

Use a maintained OIDC library rather than implementing the entire protocol and cryptographic validation yourself.

Section 12

What if you are using ForgeRock instead of Google?

Here is the interesting part.

The OIDC protocol doesn't fundamentally change when you replace Google with ForgeRock, Okta, or Keycloak. The Identity Provider changes, but the application still follows the same general process.

GoogleForgeRock
Google authorization endpointForgeRock AM authorization endpoint
Google token endpointForgeRock AM token endpoint
Google JWKS endpointForgeRock AM JWKS endpoint
Google ID tokenForgeRock-issued ID token
Google user claimsForgeRock user claims

Your application discovers the provider's configuration using its OIDC discovery URL. For ForgeRock, the exact URL depends on the deployment, realm, and version.

This is one of the benefits of implementing against standard OIDC specifications: you can support different identity providers without rewriting your entire authentication architecture.

Section 13

The complete OIDC architecture at a glance

Let's put the complete flow together. The main interactions are:

  1. 01User clicks Sign Up / Login.
  2. 02Frontend initiates authentication.
  3. 03Backend generates state, nonce, and PKCE values.
  4. 04Browser redirects to the Identity Provider.
  5. 05Identity Provider authenticates the user.
  6. 06Browser receives the authorization code through the callback.
  7. 07Backend exchanges the code for tokens.
  8. 08Backend retrieves JWKS and validates the ID token.
  9. 09Backend finds or creates the application user.
  10. 10Backend creates an application session.
  11. 11Browser accesses protected APIs using its session cookie.

The complete flow is much more than a login button. It is a coordinated interaction between the browser, frontend, backend, Identity Provider, and application database.

Section 14

Final thoughts

The biggest takeaway for me is that OIDC isn't about transferring passwords between applications.

It's about establishing trust between an application and an Identity Provider.

The Identity Provider handles authentication. Your application verifies the resulting identity assertion, manages its own user accounts, establishes a session, and enforces authorization.

Once you understand this separation, integrating Google, ForgeRock, Okta, or Keycloak becomes much easier to reason about.

And the next time you click Sign in with Google, you will know there is quite a lot happening behind that one button.

One click. Multiple systems. A carefully designed trust relationship.

Further reading

Keep reading

Building Scan Factory: an orchestrated platform for AI-powered security scanning

Event-driven orchestration, isolated sandboxes, and agent-driven remediation that ends in a reviewed pull request.

Read the article