In ASP.NET Core 10, how do AddCookie and AddOpenIdConnect work together to sign staff into an intranet through a corporate identity provider?
answer
- two schemes, two jobs
- DefaultChallengeScheme = OpenIdConnect
- SignInScheme falls back to DefaultSignInScheme, then DefaultScheme
- CallbackPath /signin-oidc
- the cookie answers every later request
basics
~20 sThe OpenID Connect handler only performs the sign-in: it redirects to the identity provider, validates the response on /signin-oidc and signs the resulting principal into the cookie scheme. From then on the cookie handler alone authenticates each request.
solid answer
~40 sYou register two schemes with different jobs. `AddAuthentication` sets `DefaultScheme` to `CookieAuthenticationDefaults.AuthenticationScheme`, so every request is authenticated from the cookie, and `DefaultChallengeScheme` to `OpenIdConnectDefaults.AuthenticationScheme`, so a failed `[Authorize]` redirects to the provider. `AddOpenIdConnect` needs `Authority` (the handler reads `/.well-known/openid-configuration` from it), `ClientId`, usually `ClientSecret`, and `ResponseType = "code"`. When the provider returns to `CallbackPath` (`/signin-oidc`), the handler checks state and the correlation cookie, redeems the code, validates the ID token, builds a `ClaimsPrincipal` and calls `SignInAsync` on its `SignInScheme`: the cookie scheme, or `DefaultSignInScheme` / `DefaultScheme` when unset. After that the provider is not contacted again until the cookie expires or a challenge happens. The handler lives in the separate `Microsoft.AspNetCore.Authentication.OpenIdConnect` package.
code
csharp · 23 linesusing Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
var oidc = builder.Configuration.GetSection("CorporateIdp");
options.Authority = oidc["Authority"];
options.ClientId = oidc["ClientId"];
options.ClientSecret = oidc["ClientSecret"];
options.ResponseType = OpenIdConnectResponseType.Code;
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
builder.Services.AddAuthorization();go deeper
Recall that the provider signs the user in once and the app then keeps a cookie, and that /signin-oidc is where the provider sends the user back.
Explain which AuthenticationOptions defaults point where, how SignInScheme falls back, and walk the challenge, callback and SignInAsync steps in order.
Diagnose broken setups: a challenge landing on /Account/Login, a SignInScheme resolving to itself, unregistered redirect URIs per host, and cookies unreadable across instances.
Decide how far the app trusts the cookie session versus the provider session, and how session lifetime and re-authentication should be set across the organisation's apps.
## Two handlers, two jobs ASP.NET Core authentication is built from **schemes**: a name bound to a handler and its options. A sign-in through an external identity provider (IdP) uses two of them: - The **cookie scheme** (`AddCookie`, name `"Cookies"`) is a *local* handler. It reads an encrypted cookie on every request and turns it back into a `ClaimsPrincipal`. - The **OpenID Connect scheme** (`AddOpenIdConnect`, name `"OpenIdConnect"`) is a *remote* handler. It knows how to send the browser to the IdP and how to process the IdP's answer, but it cannot keep a session of its own. It hands the result to another scheme, its `SignInScheme`. `AuthenticationOptions` wires them together: | Setting | Value for an intranet | Effect | |---|---|---| | `DefaultScheme` | `"Cookies"` | every request is authenticated from the cookie | | `DefaultChallengeScheme` | `"OpenIdConnect"` | an anonymous user who fails `[Authorize]` is sent to the IdP | | `OpenIdConnectOptions.SignInScheme` | `"Cookies"` | where the handler stores the result | If `SignInScheme` is left unset, a post-configure step fills it from `DefaultSignInScheme`, then `DefaultScheme`. If that fallback resolves to the OIDC scheme itself, option validation throws `InvalidOperationException` ("The SignInScheme for a remote authentication handler cannot be set to itself"). ## The round trip 1. A staff member opens `/timesheets`. Authorization fails for an anonymous user, so the middleware calls `ChallengeAsync()`, which goes to the default challenge scheme, the OIDC handler. 2. The handler loads the provider's discovery document from `Authority` + `/.well-known/openid-configuration`, builds the authorization request (client id, `redirect_uri` ending in `/signin-oidc`, scopes, and a PKCE challenge for the code flow), writes a **nonce cookie** and a **correlation cookie**, protects the original URL inside `state`, and redirects. 3. The user signs in at the IdP, which sends the browser back to `CallbackPath`, `/signin-oidc` by default. No controller handles this path: the authentication middleware lets the remote handler claim it. 4. The handler checks `state` against the correlation cookie, redeems the authorization code at the token endpoint, validates the ID token (signature, issuer, audience = `ClientId`, nonce), runs its events and builds the principal. 5. It calls `SignInAsync(SignInScheme, principal, properties)`. The cookie handler writes the session cookie, and the browser is redirected to `/timesheets`. 6. Every later request is authenticated by the **cookie handler only**. The IdP is not called again until the cookie expires or something challenges. ## Minimum options - `Authority` or `MetadataAddress`, plus `ClientId`. Option validation throws if `ClientId` is empty or no configuration source is given. - `RequireHttpsMetadata` is `true`, so an `http://` authority throws when the options are first built unless you turn it off, which is only for local development. - `ResponseType` defaults to `id_token`. Set it to `OpenIdConnectResponseType.Code` for the authorization code flow, and supply `ClientSecret` when the registration is a confidential web client. - `CallbackPath` (`/signin-oidc`) must be registered at the IdP as a redirect URI for every host the app runs on. ## Session lifetime The cookie's own settings decide how long staff stay signed in, not the ID token's `exp`. `UseTokenLifetime` (default `false`) makes the authentication properties expire with the token instead. Data Protection encrypts the cookie, so every instance of a farm must share its key ring. ## Typical mistakes - Setting only `DefaultScheme = "OpenIdConnect"` and leaving `SignInScheme` unset: the sign-in fallback points the handler at itself and option validation throws. - Forgetting `DefaultChallengeScheme`, so challenges go to the cookie handler, which redirects to its `LoginPath` (`/Account/Login`), a page the intranet does not have. - Writing a controller action for `/signin-oidc`; the handler owns that path. - Expecting `AddOpenIdConnect` to be available without a package: it ships as `Microsoft.AspNetCore.Authentication.OpenIdConnect`, outside the shared framework.
- Why does the intranet not contact the identity provider on every request?Because `DefaultScheme` points at the cookie handler. After the callback the OIDC handler signs the principal into the cookie, and later requests only decrypt that cookie. The provider is involved again only on a new challenge, for example after the cookie expires.
- What happens if you call AddOpenIdConnect but never set DefaultChallengeScheme?Challenges go to the default scheme, here the cookie handler, which redirects browsers to `LoginPath` (`/Account/Login`) instead of the provider. Either set `DefaultChallengeScheme` to the OIDC scheme or challenge it explicitly from a login endpoint.
- Where does the handler keep the URL the user originally asked for?In `AuthenticationProperties.RedirectUri`, which the handler protects with Data Protection and sends as the `state` parameter. On the callback it unprotects `state` and redirects to that URL after signing in.
A conference desk checks your passport once and prints a badge; from then on every door scanner reads only the badge, and you go back to the desk only when the badge expires.
- The OpenID Connect handler keeps its own session, so no cookie scheme is needed.
- You must write a controller action that handles /signin-oidc.
- Every request is re-validated against the identity provider after sign-in.
- Setting DefaultScheme to OpenIdConnect alone is enough; SignInScheme sorts itself out.
- AddOpenIdConnect is part of the shared framework, so no PackageReference is needed.