---
title: "Add Google Login to Your ASP.NET Core App"  
description: "Add “Sign in with Google” to an ASP.NET Core application. Create OAuth credentials in Google Cloud Console, configure the Google authentication handle"  
author: "Vaibhav Kumar"  
published: 2026-11-23  
canonical: https://www.mindstick.com/blog/307150/add-google-login-to-your-asp-net-core-app  
category: ".NET Development"  
tags: ["google login asp.net core", "asp.net core", ".net", ".net development", "step by step tutorial"]  
reading_time: 6 minutes  

---

# Add Google Login to Your ASP.NET Core App

Most people already have a Google account. Letting them sign in with it removes the friction of creating yet another password, and spares you from storing and protecting passwords yourself.

ASP.NET Core has built-in support for Google sign-in. This guide sets it up from scratch using cookie authentication, which suits server-rendered apps built with MVC, Razor Pages or Blazor Server.

## How it works

1. The user clicks **Sign in with Google**.
2. Your app redirects them to Google.
3. They sign in and agree to share basic profile information.
4. Google redirects back to your app at a **callback URL** with an authorisation code.
5. The ASP.NET Core Google handler exchanges that code for the user’s identity.
6. Your app creates a **cookie** so the user stays signed in.

This is the standard **OAuth 2.0 / OpenID Connect** flow. The library handles the protocol details.

## Step 1: Create credentials in Google Cloud Console

1. Go to the **Google Cloud Console** and create a project (or choose an existing one).
2. Configure the **OAuth consent screen** (in recent versions of the console this is under **Google Auth Platform**): app name, support email, logo, and your privacy policy and terms URLs. For apps used by anyone with a Google account, choose **External**.
3. Go to **Credentials → Create credentials → OAuth client ID**.
4. Choose **Web application**.
5. Under **Authorised redirect URIs**, add:

- `https://localhost:5001/signin-google` `https://www.yourdomain.com/signin-google`
- Use your app’s actual development port and production domain. `/signin-google` is the default callback path for the ASP.NET Core Google handler.

1. Copy the **Client ID** and **Client secret**.

For apps that only request basic sign-in scopes (email and profile), Google’s verification process is usually straightforward. Requesting sensitive scopes, like Gmail or Drive access, requires a more detailed review.

## Step 2: Add the package

```
dotnet add package Microsoft.AspNetCore.Authentication.Google
```

## Step 3: Store the secrets safely

During development, use User Secrets:

```
dotnet user-secrets init
dotnet user-secrets set "Authentication:Google:ClientId" "<your-client-id>"
dotnet user-secrets set "Authentication:Google:ClientSecret" "<your-client-secret>"
```

In production, use environment variables (`Authentication__Google__ClientSecret`), IIS application settings, or a vault like Azure Key Vault. Never commit the client secret to Git.

## Step 4: Configure authentication

In `Program.cs`:

```
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
    })
    .AddCookie(options =>
    {
        options.LoginPath = "/login";
        options.ExpireTimeSpan = TimeSpan.FromDays(7);
        options.SlidingExpiration = true;
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.SameSite = SameSiteMode.Lax;
    })
    .AddGoogle(options =>
    {
        options.ClientId = builder.Configuration["Authentication:Google:ClientId"]!;
        options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]!;
        options.SaveTokens = false; // we only need identity, not Google API access
    });

builder.Services.AddAuthorization();
builder.Services.AddRazorPages();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

// Start the Google sign-in
app.MapGet("/login", (string? returnUrl) =>
    Results.Challenge(
        new AuthenticationProperties { RedirectUri = SafeReturnUrl(returnUrl) },
        new[] { GoogleDefaults.AuthenticationScheme }));

// Sign out of our app (doesn't sign the user out of Google itself)
app.MapPost("/logout", async (HttpContext ctx) =>
{
    await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Results.Redirect("/");
}).RequireAuthorization();

// A protected page showing who's signed in
app.MapGet("/me", (ClaimsPrincipal user) => Results.Ok(new
{
    Name = user.Identity?.Name,
    Email = user.FindFirstValue(ClaimTypes.Email),
    GoogleId = user.FindFirstValue(ClaimTypes.NameIdentifier)
})).RequireAuthorization();

app.MapRazorPages();
app.Run();

// Only allow redirects back into our own site (prevents open redirects)
static string SafeReturnUrl(string? url) =>
    !string.IsNullOrEmpty(url) && url.StartsWith('/') && !url.StartsWith("//") ? url : "/";
```

### What’s going on

- **Two schemes work together.** The **cookie** scheme remembers the signed-in user. The **Google** scheme handles the sign-in round trip. `DefaultChallengeScheme = Google` means that visiting a protected page sends unauthenticated users to Google automatically.
- **The callback path** `/signin-google` is handled by the middleware for you. You don’t write a controller for it.
- **`SafeReturnUrl`** prevents attackers from crafting a login link that redirects users to a malicious site afterwards.
- **Logout** removes your app’s cookie. It doesn’t sign the user out of their Google account, which is expected behaviour.

## Step 5: Add a sign-in button

In a Razor page or layout:

```
@if (User.Identity?.IsAuthenticated == true)
{
    <span>Hello, @User.Identity.Name</span>
    <form method="post" action="/logout">
        @Html.AntiForgeryToken()
        <button type="submit">Sign out</button>
    </form>
}
else
{
    <a href="/login?returnUrl=@Context.Request.Path">Sign in with Google</a>
}
```

Follow Google’s **branding guidelines** for the sign-in button’s appearance.

## Step 6: Link Google users to your own user records

Google tells you who someone is; your app decides what they can do. Usually you’ll want a `Users` table keyed by the Google user ID (the `NameIdentifier` claim, which is stable), not by email, since email addresses can change.

Hook into the sign-in event to create or update your user record and add your own roles:

```
.AddGoogle(options =>
{
    // ... ClientId, ClientSecret as before ...
    options.Events.OnCreatingTicket = async ctx =>
    {
        var googleId = ctx.Principal!.FindFirstValue(ClaimTypes.NameIdentifier)!;
        var email = ctx.Principal!.FindFirstValue(ClaimTypes.Email);

        var users = ctx.HttpContext.RequestServices.GetRequiredService<IUserService>();
        var appUser = await users.FindOrCreateAsync(googleId, email, ctx.Principal!.Identity!.Name);

        var identity = (ClaimsIdentity)ctx.Principal!.Identity!;
        foreach (var role in appUser.Roles)
            identity.AddClaim(new Claim(ClaimTypes.Role, role));
    };
});
```

(`IUserService` here is your own service that reads and writes your database.)

If you want a full user system with local accounts, two-factor authentication and multiple external providers, use **ASP.NET Core Identity**, which integrates Google sign-in into its external login flow.

## Restricting sign-in to your company domain

For internal apps used only by your Google Workspace domain, check the `hd` (hosted domain) claim or the email domain in `OnCreatingTicket`, and reject everyone else:

```
if (!email?.EndsWith("@yourcompany.com", StringComparison.OrdinalIgnoreCase) ?? true)
{
    ctx.Fail("Only company accounts are allowed.");
}
```

You can also set the OAuth consent screen to **Internal**, which limits access to your Workspace organisation.

## Common errors

**`Error 400: redirect_uri_mismatch`** The callback URL your app sends doesn’t exactly match one registered in Google Cloud Console. Check the scheme (`http` vs `https`), host, port and path. Behind a reverse proxy or load balancer that terminates HTTPS, your app may think it’s running on `http`. Configure **Forwarded Headers middleware** so it sees the original scheme and host.

**Correlation failed** Usually a cookie problem: the correlation cookie was lost during the round trip. Causes include running over HTTP while cookies require HTTPS, `SameSite` issues, clock problems, or multiple servers without shared **Data Protection keys**. In web farms, store Data Protection keys somewhere shared (a database, Redis, or blob storage).

**Users signed out after deployment or app pool recycle** Also a Data Protection keys issue. Persist keys to a location that survives restarts.

**Name or email claim is empty** Make sure the default scopes (`openid`, `profile`, `email`) are requested. They are by default in the Google handler.

## Privacy and compliance

You’re receiving personal data: name, email address and possibly profile photo. Publish a privacy policy explaining how you use it, store only what you need, and treat it according to the DPDP Act. Google also requires a privacy policy link on the consent screen for external apps.

## That’s it

With one package, a few lines of configuration and a Google Cloud OAuth client, your ASP.NET Core app can let users sign in with their Google accounts: no passwords to store, reset or leak.

Keep secrets out of source code, register exact redirect URIs, link Google IDs to your own user records, protect against open redirects, and persist Data Protection keys in production. Then Google sign-in will just work, quietly, which is exactly what users expect.

---

Original Source: https://www.mindstick.com/blog/307150/add-google-login-to-your-asp-net-core-app

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
