Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 5 · Lesson 45 · 7 min read

OpenID Connect with PKCE in ASP.NET Core and React

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: The Flow on the Wire and the ASP.NET Core Configuration
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Distinguish OAuth 2.0 from OpenID Connect, walk through the authorization code flow with PKCE step by step, identify the purpose of state, nonce and redirect URI checks, choose between hosting your own identity server and using a provider such as Microsoft Entra ID, and wire sign-in into ASP.NET Core.

Concept Explanation

OAuth 2.0 is a framework for delegating access: it lets an application obtain a limited access token to call an API on a user's behalf without the user handing over their password. It says nothing about who the user is. OpenID Connect, OIDC, adds an identity layer on top: it defines an ID token, a signed JWT that tells the application who authenticated, when, and how, plus a standard user info endpoint and a discovery document at a well-known address that publishes the provider's endpoints and signing keys. When people say sign in with Microsoft or Google, they mean OIDC, and the two protocols together let you delegate authentication entirely to a specialist.

The flow used today is the authorization code flow with PKCE. The application sends the user's browser to the provider's authorize endpoint with its client identifier, the requested scopes, a redirect URI, a random state value, and a code challenge. The user signs in at the provider, so your application never sees their password, and the provider redirects back with a short-lived authorization code. The application then exchanges that code, together with the original code verifier, at the token endpoint for an ID token, an access token, and optionally a refresh token. Because the exchange is a direct back-channel call, tokens are never exposed in the browser's URL, unlike the older implicit flow, which the current OAuth security best practice, RFC 9700, advises against.

Each parameter defends against a specific attack. State is a random value the client generates and later checks, tying the response to the request and preventing cross-site request forgery against the login callback. PKCE, Proof Key for Code Exchange, RFC 7636, makes a stolen authorization code useless: the client creates a random verifier, sends only its hash as the challenge, and must present the original verifier during the exchange, so an attacker who intercepts the code cannot redeem it. Nonce is embedded in the ID token and checked to prevent replay of tokens. The redirect URI must match a pre-registered value exactly, so a code cannot be delivered to an attacker's address. Validate the ID token's issuer, audience, signature, expiry, and nonce, all handled by the framework if configured properly.

Then decide who runs the identity system. Building an OIDC provider yourself means owning password storage, MFA, account recovery, abuse detection, and protocol correctness, which is a great deal of security surface. Most products use a managed provider: Microsoft Entra ID for work and school accounts, Entra External ID for customer-facing sign-in, Auth0, Okta, or Keycloak self-hosted. Microsoft stopped selling Azure AD B2C to new customers in May 2025 in favor of Entra External ID, so check current guidance for new projects. Note that the flow above describes a confidential client, a server-side application that can keep a client secret. A pure browser SPA is a public client and must use PKCE without a secret, which is why Day 46 moves the OIDC handling to a backend.

ElementPurposeAttack it prevents
Authorization codeShort-lived proof of sign-in delivered via redirectTokens exposed in URLs and history
PKCE verifier and challengeBinds the exchange to the original clientStolen or intercepted authorization codes
stateTies the response to the requestCSRF on the callback
nonceTies the ID token to the sessionToken replay
Exact redirect URI matchRestricts where codes are sentCode delivery to an attacker's site
ID token validationVerifies issuer, audience, signature, expiryForged or misdirected identity tokens

Worked Example: The Flow on the Wire and the ASP.NET Core Configuration

The requests below show the two legs of the flow with placeholders. The configuration then wires a server-side ASP.NET Core application to Microsoft Entra ID as a confidential client using a cookie session.

Code
1. Browser is redirected to the provider (authorize endpoint):
GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
  ?client_id=11111111-2222-3333-4444-555555555555
  &response_type=code
  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fsignin-oidc
  &scope=openid%20profile%20email%20api%3A%2F%2Fnotes-api%2Fnotes.read
  &state=k3J9x...          <- random, checked on return
  &nonce=Zr8pQ...          <- random, appears inside the ID token
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256

2. User signs in and consents. Provider redirects back:
GET https://app.example.com/signin-oidc?code=0.AAAA...&state=k3J9x...

3. Server exchanges the code on the back channel (never visible to the browser):
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
  grant_type=authorization_code&code=0.AAAA...&redirect_uri=...
  &client_id=...&client_secret=<from Key Vault>&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

4. Response: id_token, access_token, refresh_token (validated and stored server-side)
C#
builder.Services
    .AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(o =>
    {
        o.Cookie.Name = "__Host-session"; o.Cookie.HttpOnly = true;
        o.Cookie.SecurePolicy = CookieSecurePolicy.Always; o.Cookie.SameSite = SameSiteMode.Lax;
    })
    .AddOpenIdConnect(o =>
    {
        o.Authority = $"https://login.microsoftonline.com/{builder.Configuration["Entra:TenantId"]}/v2.0";
        o.ClientId = builder.Configuration["Entra:ClientId"];
        o.ClientSecret = builder.Configuration["Entra:ClientSecret"];      // from Key Vault or user secrets, never source control
        o.ResponseType = OpenIdConnectResponseType.Code;                    // authorization code flow
        o.UsePkce = true;                                                   // on by default, stated for clarity
        o.CallbackPath = "/signin-oidc";                                    // must exactly match the registered redirect URI
        o.SaveTokens = true;                                                // keep tokens in the encrypted session ticket
        o.GetClaimsFromUserInfoEndpoint = false;
        o.MapInboundClaims = false;
        o.Scope.Clear();
        foreach (var s in new[] { "openid", "profile", "email", "offline_access" }) o.Scope.Add(s);
        o.TokenValidationParameters.NameClaimType = "name";
        // state, nonce and ID token validation are performed by the handler automatically.
    });

app.MapGet("/auth/login", () => Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }))
   .AllowAnonymous();

Two operational details matter as much as the code. Register only exact redirect URIs for each environment in the provider, never wildcards, since a permissive redirect is the most common OAuth misconfiguration. And treat the client secret as a credential like any other: store it in Key Vault, rotate it, and prefer certificates or federated managed identity credentials over long-lived secrets where the provider supports them.

The browser is sent to the identity provider with a state, nonce and code challenge. The provider returns a short-lived code, which the BFF redeems on the back channel with the code verifier and client secret, then keeps the tokens server side.
The browser is sent to the identity provider with a state, nonce and code challenge. The provider returns a short-lived code, which the BFF redeems on the back channel with the code verifier and client secret, then keeps the tokens server side.

Real-World Examples

  • The OAuth 2.0 Security Best Current Practice, published as RFC 9700 in January 2025, consolidates a decade of lessons: it recommends the authorization code flow with PKCE for all clients, discourages the implicit flow and the resource owner password credentials grant, and requires exact redirect URI matching. The forthcoming OAuth 2.1 consolidates the same rules into the core specification.
  • Microsoft Entra ID, formerly Azure Active Directory, is the identity provider behind Microsoft 365 and a large share of enterprise sign-in, and it issues OIDC and OAuth 2.0 tokens using the same standards described here. Applications registered with it validate tokens using its published discovery document and rotating signing keys, which is why using the standard libraries rather than custom code keeps you correct as keys and policies change.
Key TakeawaysOIDC adds identity to OAuth 2.0, and the authorization code flow with PKCE is the standard, secure way to sign users in through a provider. Each parameter, state, nonce, PKCE, and exact redirect URIs, blocks a specific attack, so leave the framework's validation on. Prefer a managed identity provider over building your own, and keep client secrets and refresh tokens on the server.

Review Questions & Answers

OAuth 2.0 is about authorization: it issues access tokens that let an application call an API on a user's behalf, and says nothing about who the user is. OpenID Connect builds an authentication layer on top, adding an ID token that states who signed in, standard claims, and a discovery mechanism. Sign-in with a provider uses OIDC, and calling APIs afterward uses the OAuth access token.

The client generates a secret verifier and sends only its hash, the challenge, in the authorization request. To redeem the code, it must present the original verifier, which the provider checks against the challenge. An attacker who intercepts the code from the redirect does not know the verifier, so the code cannot be exchanged for tokens.

The provider sends the authorization code to the redirect address, so a permissive rule lets an attacker craft a request whose redirect points to a location they control, or to an open redirect on your site, and capture the code. Exact matching means codes are delivered only to addresses you deliberately registered.

Identity involves password storage, multi-factor authentication, account recovery, breach detection, rate limiting, and constant protocol updates, each a place to make a costly mistake. A specialist provider invests continuously in those and gets scrutinized by many customers and researchers. Your application then only validates tokens, a much smaller surface to get right.