In ASP.NET Core, how does AddGoogle let users sign in with a Google account, and what does its handler do when Google redirects back?
answer
- a separate NuGet package
- client id and secret from Google
- CallbackPath /signin-google
- code exchange, then the userinfo call
- signed into a cookie scheme
basics
~20 sAddGoogle registers an OAuth-based remote handler: a challenge redirects to Google, and on /signin-google it exchanges the code, reads Google's userinfo endpoint, maps the JSON to claims and signs the principal into a cookie scheme.
solid answer
~40 sAdd the `Microsoft.AspNetCore.Authentication.Google` package, create OAuth credentials in Google's console with `https://<host>/signin-google` as an authorized redirect URI, and register `AddAuthentication(...).AddCookie().AddGoogle(o => { o.ClientId = ...; o.ClientSecret = ...; })` with the cookie as default scheme and `GoogleDefaults.AuthenticationScheme` as the challenge scheme. A challenge redirects to Google with `state`, the `openid profile email` scopes and a PKCE challenge (`GoogleOptions` sets `UsePkce = true`). Google returns to `/signin-google`, where the handler checks `state` against its correlation cookie, exchanges the code for an access token, calls Google's userinfo endpoint and maps the JSON to claims such as `ClaimTypes.NameIdentifier`, `Name` and `Email`. It then calls `SignInAsync` on its sign-in scheme, the cookie, which authenticates every later request.
code
csharp · 14 linesusing Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
options.ClientId = builder.Configuration["Authentication:Google:ClientId"]!;
options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]!;
});go deeper
Recall the package, the client id and secret, the /signin-google redirect URI, and that a cookie keeps the user signed in afterwards.
Explain the round trip: correlation cookie and state, code exchange, the userinfo call, claim mapping to ClaimTypes, and SignInAsync on the cookie scheme.
Handle the edges: redirect URI mismatches per host, linking external logins with Identity, keeping refresh tokens with AccessType, and why sign-out stays local.
Decide whether consumer social logins belong beside the corporate provider, and how external identities map to accounts the organisation controls.
## What AddGoogle registers `AddGoogle` comes from the **`Microsoft.AspNetCore.Authentication.Google`** NuGet package; it is not part of the shared framework. It registers a scheme named `"Google"` (`GoogleDefaults.AuthenticationScheme`) whose handler, `GoogleHandler`, derives from `OAuthHandler<GoogleOptions>`. It is an **OAuth 2.0** handler with Google's endpoints preset, not the OpenID Connect handler. Like every remote handler it can start a sign-in and process the answer, but it keeps no session itself: it hands the user to a **sign-in scheme**, normally a cookie. ## Wiring it up 1. In Google's developer console, create OAuth client credentials for a web application and add `https://<your-host>/signin-google` as an authorized redirect URI for every host the app runs on. 2. Keep the client id and secret out of source control, for example in user secrets during development. 3. In `Program.cs`, register a cookie scheme as `DefaultScheme` and Google as `DefaultChallengeScheme`, then call `AddCookie()` and `AddGoogle(...)` with the two credentials. 4. Protect pages with `[Authorize]`, or offer a "Sign in with Google" button that challenges the Google scheme. ## What happens on the round trip 1. An anonymous user hits a protected page; authorization challenges the Google scheme. 2. The handler writes a **correlation cookie**, protects the return URL in `state`, and redirects to Google's authorization endpoint with the scopes `openid`, `profile` and `email` and a PKCE `code_challenge`. `GoogleOptions` turns PKCE on, while the base `OAuthOptions` leaves `UsePkce` false. 3. The user signs in at Google and consents. Google redirects to `/signin-google` with a code. 4. The handler, not a controller, claims that path: it checks `state` and the correlation cookie, then posts the code with the client secret and PKCE verifier to Google's token endpoint. 5. With the access token it calls Google's **userinfo** endpoint and runs its `ClaimActions` over the JSON. 6. It calls `SignInAsync` on its sign-in scheme. The cookie handler writes the session cookie, and the browser returns to the original page. 7. Later requests are authenticated by the **cookie only**; Google is not contacted again. ## The claims you get `GoogleOptions` maps userinfo keys to the long `ClaimTypes` URIs: | Userinfo key | Claim type | |---|---| | `sub` (or `id`) | `ClaimTypes.NameIdentifier` | | `name` | `ClaimTypes.Name` | | `given_name` | `ClaimTypes.GivenName` | | `family_name` | `ClaimTypes.Surname` | | `email` | `ClaimTypes.Email` | Use `NameIdentifier` as the stable key for a user; an email address can change. Add more keys with `options.ClaimActions.MapJsonKey(...)`. ## Options worth knowing - `SaveTokens` (default `false`) stores the tokens in the cookie for later calls to Google APIs. - `AccessType = "offline"` asks Google for a refresh token by sending `access_type=offline`. - `Scope.Add(...)` requests extra Google API scopes. - `Events.OnCreatingTicket` lets you inspect the userinfo JSON and add claims. ## With ASP.NET Core Identity When the app uses Identity, `AddIdentity` sets `DefaultSignInScheme` to the external cookie (`IdentityConstants.ExternalScheme`). Google's result lands there briefly, and Identity's external-login flow links it to a local account before issuing the application cookie. ## Signing out `GoogleHandler` does not implement `IAuthenticationSignOutHandler`, so `SignOutAsync("Google")` throws `InvalidOperationException`. Sign the user out of the cookie scheme; the user's Google session in the browser stays, as it should for a social login. ## When the callback fails A failure on `/signin-google` surfaces as an `AuthenticationFailureException` ("An error was encountered while handling the remote login.") whose inner message names the failing step: - **"Correlation failed."**: the correlation cookie did not come back. It is written with `SameSite=None` and is always `Secure`, so a browser talking to the app over plain HTTP drops it. - **"Failed to retrieve access token."**: Google refused the code exchange, typically a wrong client secret or a redirect URI that differs from the one registered. - **"Failed to retrieve user information from remote server."**: the userinfo call failed. `Events.OnRemoteFailure` lets you log the failure and redirect to a friendly page, calling `context.HandleResponse()` so the exception is not thrown. ## Common mistakes - Forgetting the package reference and looking for `AddGoogle` in the framework. - Registering `http://localhost/signin-google` but running on a different port or scheme, which Google rejects as a redirect mismatch. - Writing a `/signin-google` action, which the handler already owns. - Treating `ClaimTypes.Email` as the user's permanent identifier.
- How does AddGoogle differ from pointing AddOpenIdConnect at Google?`AddGoogle` is an OAuth handler with Google's endpoints preset: it builds the user from the userinfo response fetched with the access token. `AddOpenIdConnect` reads Google's discovery document, validates the signed ID token and its nonce, and exposes the full `OpenIdConnectEvents` set. Both sign into a cookie scheme.
- How would the app keep a token to call a Google API later?Set `SaveTokens = true` so the handler stores `access_token` (and `refresh_token`, if Google issued one) in the cookie's authentication properties, add the API's scope, and set `AccessType = "offline"` if a refresh token is needed. Read them with `HttpContext.GetTokenAsync("access_token")`.
- AddGoogle is part of the shared framework, so no package reference is needed.
- After the callback, each request asks Google whether the user is still signed in.
- You must write a controller action that handles /signin-google.
- Calling SignOutAsync with the Google scheme signs the user out of Google.
- AddGoogle is the OpenID Connect handler and validates Google's ID token.