bloggrammer logo

John Ansa

C# .NET | MERN | DevOps | LLMs
Founder @AlgoCollab
Contact
Skills
Share: 

Integrating Google Authentication in ASP.NET Web API

Authentication is a crucial aspect of web applications, ensuring that users can securely access resources and information.

Google authentication provides a convenient and secure way for users to log into applications using their Google accounts.

In this guide, we'll explore how to implement Google authentication in ASP.NET Web API project, allowing users to sign in using their Google credentials.

Integrating Google Authentication in ASP.NET Web API

 

Understanding Google Authentication

What is Google Authentication?

Google Authentication, also known as Google Sign-In, is a mechanism that allows users to log in to third-party applications or websites using their Google account credentials. It employs the OAuth 2.0 protocol, an open-standard authorization framework that enables secure access to user data without disclosing passwords to third-party applications.

How Google Authentication Works

Google Authentication relies on OAuth 2.0, which facilitates secure access to a user's information without sharing their password. It involves the exchange of tokens that grant access to specific resources.

The Workflow of Google Authentication

Google Authentication Flow
Image Credit: Google Sign-In for server-side apps
  1. User Requests Access: When users try to access a service or application that implements Google Authentication, they are redirected to Google's authentication servers to log in.

  2. User Authorization: The user is prompted to grant permission for the application to access specific information associated with their Google account, such as profile data, email address, or contacts.

  3. Authentication & Token Exchange: Once the user grants permission, Google's authentication servers verify the user's identity. Upon successful authentication, Google generates an access token and an ID token, which are sent back to the application.

  4. Accessing Services: The application can now use these tokens to make requests to Google API services on behalf of the user. The tokens serve as a means of authentication and authorization, allowing access to the requested resources without revealing the user's password.

 

Why Use Google Authentication in ASP NET Web API?

Google Authentication offers a convenient and secure method for users to access applications without creating separate credentials. 

Users can log in to your web app using their existing Google credentials, eliminating the need to create a new account and remember new credentials.

This simplifies the registration and login process, potentially increasing user engagement and retention.

Utilizing this Google authentication method within ASP.NET Web API alleviates the developer from the responsibility of handling user passwords and login credentials.

 

Prerequisites

Before we begin, ensure you have the following:

  1. Visual Studio is installed on your machine for .NET 6 and later versions.
  2. Basic knowledge of .NET Web API development.
  3. Access to the Google Developer Console to obtain the necessary credentials.

 

Steps for Creating Google Client Secret and Client ID on Google Developer Console

  1. Create a Project:

    google developer console
    create new project on google developer console
    • Click on "Select a project" (or the project dropdown) at the top of the page and choose "New Project."
    google developer console project name
    • Click on "Select a project" (or the project dropdown) at the top of the page and choose "New Project."
    • Enter a name for your project and click "Create."
  2. Create OAuth Credentials:

    google authentication credentials
    • Navigate to the "Credentials" tab from the left sidebar.
    • Click on the "Create credentials" dropdown and select "OAuth client ID."
    • Choose the application type as "Web application."
  3. Configure OAuth Consent Screen:

    configure consent screen google auth
    • If prompted, configure the OAuth consent screen by providing necessary information like app name, user support email, and scopes.
    • Save the changes.
    google authentication consent screen
  4. Set Authorized Redirect URIs:

    google auth redirect uri
    • In the OAuth client creation wizard, under "Authorized redirect URIs," enter the URI where Google should redirect after authentication. For local development, it might be https://localhost:port/.
    •                 https://yourdomain.com/signin-google
                      
    • Click "Create" to generate the Client ID and Client Secret.
  5. Obtain Client ID and Client Secret:

    google authentication client secret
    • Once the OAuth client is created, Google will provide you with a Client ID and Client Secret. These are essential for integrating Google authentication into your ASP.NET Core Web API.

Now that you have obtained the Client ID and Client Secret, let's proceed with integrating Google authentication into your ASP.NET Web API.

 

Integrating Google Authentication in ASP.NET Web API

Step 1: Create ASP.NET Web API Project

asp net web api

Step 2: Install Required NuGet Packages

google authentication nuget package
Install-Package Microsoft.AspNetCore.Authentication.Google

Step 3: Configure Google Authentication

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
    options.ClientId = "YOUR_GOOGLE_CLIENT_ID";
    options.ClientSecret = "YOUR_GOOGLE_CLIENT_SECRET";
});

Step 4: Enable Authentication

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

Step 5: Implement Controllers and Routes

 
  [ApiController]
  [Route("[controller]")]
  public class AccountController : ControllerBase
  {
      [HttpGet("login")]
      public IActionResult Login()
      {
          var props = new AuthenticationProperties { RedirectUri = "account/signin-google" };
          return Challenge(props, GoogleDefaults.AuthenticationScheme);
      }
      [HttpGet("signin-google")]
      public async Task<IActionResult> GoogleLogin()
      {
        var response = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        if(response.Principal == null) return BadRequest();
            
        var name = response.Principal.FindFirstValue(ClaimTypes.Name);
        var givenName = response.Principal.FindFirstValue(ClaimTypes.GivenName);
        var email = response.Principal.FindFirstValue(ClaimTypes.Email);
        //Do something with the claims
        // var user = await UserService.FindOrCreate(new { name, givenName, email});

        return Ok();
      }
  }

Note: Ensure that the RedirectUri is not a mismatch.

Step 6: Testing the Implementation

 

Conclusion

Integrating Google Authentication in an ASP.NET Web API project significantly enhances user experience by providing a familiar and secure login method. Following the steps outlined above, you can seamlessly incorporate Google Authentication, leveraging its robust features within your application.

However, it's important to note that while there are numerous advantages to using Google Authentication, it might not be suitable for every application. Some users may prefer not to link their Google accounts to other services, so offering alternative authentication methods could be beneficial to cater to different user preferences. Additionally, relying solely on third-party authentication means your app's availability could be affected if there are any issues with Google's authentication services.

This tutorial should help you integrate Google Authentication using OpenID Connect into your ASP.NET Web API project. Adjustments may be needed based on specific project requirements or updates in libraries.

Remember to handle errors gracefully and securely store user information obtained from Google's authentication in your application's database or session for further use.

, , , , ,