Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Integrating Google OAuth 2.0 Login in ASP.NET Core: A Comprehensive Guide

Integrating Google OAuth 2.0 Login in ASP.NET Core: A Comprehensive Guide

Date- Apr 29,2026 78
google oauth

Overview

OAuth 2.0 is an industry-standard protocol for authorization that allows third-party applications to obtain limited access to user accounts on an HTTP service, such as Google. By using OAuth 2.0, applications can authenticate users without needing to handle passwords directly, thereby enhancing security and user experience. This is particularly important in today's digital landscape where security breaches and data leaks are prevalent.

The need for OAuth 2.0 arose from the challenge of managing user credentials securely while providing seamless access to resources across different platforms. Real-world applications include social media platforms, online banking, and enterprise applications where users can log in with their existing Google accounts. This not only simplifies the login process for users but also reduces the burden on developers to manage sensitive information.

Prerequisites

  • ASP.NET Core: Familiarity with building applications using ASP.NET Core framework.
  • C#: Understanding the basics of C# programming language.
  • OAuth 2.0: Basic knowledge of OAuth 2.0 concepts, including authorization and token exchange.
  • Google Developer Console: Access to create and manage Google API credentials.
  • NuGet Packages: Familiarity with managing NuGet packages in ASP.NET Core projects.

Setting Up Google Credentials

Before you can integrate Google OAuth 2.0 login, you need to create project credentials in the Google Developer Console. This process involves registering your application and setting up the necessary OAuth consent screen.

1. Go to the Google Developer Console.

2. Create a new project by clicking on the project dropdown and selecting 'New Project'.

3. Once your project is created, navigate to the 'Credentials' section and click on 'Create Credentials' > 'OAuth Client ID'.

4. Configure the consent screen by specifying the application name, support email, and any necessary scopes.

5. Under 'Application type', select 'Web application' and specify the authorized redirect URIs, such as `https://localhost:5001/signin-google`.

6. Save your credentials; you will receive a Client ID and Client Secret which are required for your ASP.NET Core application.

Understanding Redirect URIs

Redirect URIs are crucial in OAuth 2.0 as they define where the user will be sent after authentication. Ensure that the redirect URIs specified in the Google Developer Console match those configured in your ASP.NET Core application to avoid any authentication errors.

Configuring ASP.NET Core Application

Now that you have your Google credentials, the next step is to configure your ASP.NET Core application to use these credentials for authentication.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddGoogle(options =>
        {
            options.ClientId = "YOUR_CLIENT_ID";
            options.ClientSecret = "YOUR_CLIENT_SECRET";
        });

        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

This code block initializes the authentication services in the Startup class of your ASP.NET Core application. It sets up cookie authentication as the default scheme and configures Google authentication with your Client ID and Client Secret.

1. The AddAuthentication method defines the default authentication scheme.

2. The AddCookie method adds cookie-based authentication, which is necessary for managing user sessions.

3. The AddGoogle method configures Google authentication using the provided Client ID and Client Secret.

4. The UseAuthentication and UseAuthorization methods are essential for enabling authentication and authorization middleware in the request pipeline.

Testing the Authentication Flow

After configuring the authentication, you can test the login flow by adding a login button to your views that redirects users to the Google login page.

@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Google

Login with Google

This link directs users to the login action in your account controller. You should create this action to handle the login request.

Implementing Login and Logout Actions

Next, create the account controller to handle login and logout actions. This controller will also process the authentication result from Google.

public class AccountController : Controller
{
    [HttpGet]
    public IActionResult Login(string returnUrl = null)
    {
        var redirectUrl = Url.Action("LoginCallback", "Account", new { returnUrl });
        var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
        return Challenge(properties, GoogleDefaults.AuthenticationScheme);
    }

    [HttpGet]
    public async Task LoginCallback(string returnUrl = null)
    {
        var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        if (result?.Principal == null)
        {
            return RedirectToAction(nameof(Login));
        }

        // Process user information
        var claimsIdentity = (ClaimsIdentity)result.Principal.Identity;
        var email = claimsIdentity.FindFirst(ClaimTypes.Email)?.Value;

        // Perform user sign-in logic here

        return LocalRedirect(returnUrl ?? "/");
    }

    [HttpPost]
    public IActionResult Logout()
    {
        HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Index", "Home");
    }
}

1. The Login method initiates the login process by redirecting the user to Google for authentication. The Challenge method triggers the Google authentication flow.

2. The LoginCallback method handles the callback from Google. It checks if the user is authenticated and processes the user claims, such as their email address.

3. The Logout method signs the user out of the application and redirects them to the home page.

Handling User Claims

Claims are key-value pairs associated with authenticated users. In the LoginCallback method, you can extract and store claims for user identification and authorization within your application.

Edge Cases & Gotchas

It is essential to handle specific edge cases when implementing Google OAuth 2.0 authentication to ensure a smooth user experience.

Invalid Redirect URIs

If the redirect URI specified in the Google Developer Console does not match the one used in your application, authentication will fail. Ensure that your URIs are correctly configured.

Token Expiration

OAuth 2.0 tokens have expiration times. Make sure to handle token refresh logic or prompt users to re-authenticate when their session expires.

if (result?.Principal == null)
{
    return RedirectToAction(nameof(Login));
}

Performance & Best Practices

When integrating Google OAuth 2.0, consider the following best practices for optimal performance and security:

Use HTTPS

Always use HTTPS to secure communication between your application and Google. This prevents potential man-in-the-middle attacks.

Limit Scopes

Request only the necessary scopes required for your application to function. This minimizes the risk associated with granting excessive permissions.

Implement Rate Limiting

Google APIs have usage limits. Implement rate limiting in your application to handle excessive requests gracefully.

Real-World Scenario: Simple Web Application with Google Login

Let’s tie together everything we have learned by creating a simple web application that allows users to log in using their Google accounts and displays their profile information.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [Authorize]
    public IActionResult Profile()
    {
        var email = User.FindFirst(ClaimTypes.Email)?.Value;
        return View("Profile", email);
    }
}

In this controller, the Profile action is protected by the [Authorize] attribute, ensuring that only authenticated users can access it. The user’s email is retrieved from the claims and passed to the view.

@model string

Your Profile

Email: @Model

This view displays the logged-in user's email address. The complete application integrates Google OAuth 2.0 login, allowing users to authenticate and view their profile information securely.

Conclusion

  • Google OAuth 2.0 is a powerful tool for secure user authentication.
  • Proper configuration of Google credentials and redirect URIs is critical for successful integration.
  • Implementing login and logout functionalities requires managing user claims effectively.
  • Handling edge cases and adhering to best practices enhances security and user experience.
  • By following this guide, you can create robust applications that leverage social logins seamlessly.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Integrating Google Gemini API with ASP.NET Core: A Comprehensive Guide
May 04, 2026
Integrating LinkedIn OAuth in ASP.NET Core for Professional Login
May 01, 2026
Integrating Twitter X OAuth 2.0 in ASP.NET Core: A Comprehensive Guide
Apr 30, 2026
Implementing GitHub OAuth Integration in ASP.NET Core for Seamless User Login
Apr 30, 2026
Previous in ASP.NET Core
Integrating Plivo SMS API with ASP.NET Core: A Comprehensive Guid…
Next in ASP.NET Core
Facebook Login Integration in ASP.NET Core with OAuth 2.0: A Comp…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 366 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26191 views
  • Exception Handling Asp.Net Core 20938 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20391 views
  • How to implement Paypal in Asp.Net Core 19753 views
  • Task Scheduler in Asp.Net core 17705 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor