X

Mastering OAuth 2.0 Authentication in ASP.NET Core

Introduction

In the world of web development, secure authentication and authorization are paramount to protect user data and resources. One widely-adopted protocol for handling authentication is the OAuth 2.0 framework. This article will guide you through implementing OAuth 2.0 authentication in an ASP.NET Core application, using Google as the identity provider (IdP) for demonstration purposes.

Understanding OAuth 2.0

OAuth 2.0 is an open standard for authorization that allows external services to access your data without you having to share your credentials. It defines four grant flows, of which the Authorization Code Grant with PKCE (Proof Key for Code Exchange) is commonly used in server-side applications like ASP.NET Core.

Prerequisites

  1. Visual Studio or Visual Studio Code with the .NET workload installed.
  2. A Google Cloud Platform (GCP) project with OAuth 2.0 client ID credentials for a web application.
  3. Basic understanding of ASP.NET Core and C#.

Setting up the project

First, create a new ASP.NET Core MVC project with individual user accounts:

dotnet new mvc -n OAuthExample --auth Individual
		
Copied

Configuring Google as an external login provider

  1. Open the appsettings.json file and add the Google authentication configuration:
"Authentication": {
  "Google": {
    "ClientId": "your_client_id_here",
    "ClientSecret": "your_client_secret_here",
    "CallbackPath": "/signin-google"
  }
}
		
Copied
  1. In the Startup.cs file, add the Google authentication services in the ConfigureServices method:
services.AddAuthentication()
  .AddGoogle(options =>
  {
      options.ClientId = Configuration["Authentication:Google:ClientId"];
      options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
      options.CallbackPath = Configuration["Authentication:Google:CallbackPath"];
  });
		
Copied
  1. Configure the authentication middleware in the Configure method:
app.UseAuthentication();
app.UseAuthorization();
		
Copied
  1. In the Startup.cs file, add the Google authentication services in the ConfigureServices method:
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});
		
Copied

Adding Google login to your application

  1. In the Views/Shared/_LoginPartial.cshtml file, add a Google login link:
@if (User.Identity.IsAuthenticated)
{
    <span>Hello, @User.Identity.Name!</span>
    <a asp-area="" asp-controller="Account" asp-action="Logout">Logout</a>
}
else
{
    <a asp-area="" asp-controller="Account" asp-action="Login">Login</a> |
    <a asp-area="" asp-controller="Account" asp-action="ExternalLogin">Login with Google</a>
}
		
Copied
  1. Add an ExternalLogin action in the AccountController.cs file:
[HttpPost]
public IActionResult ExternalLogin(string provider)
{
    var redirectUrl = Url.Action("ExternalLoginCallback", "Account");
    var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
    return Challenge(properties, provider);
}
		
Copied
  1. Add an ExternalLoginCallback action to handle the response from Google:
public async Task<IActionResult> ExternalLoginCallback()
{
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        return RedirectToAction("Login");
    }

    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
    if (result.Succeeded)
    {
        return RedirectToAction("Index", "Home");
    }
    else
    {
        // Handle sign-in failure
        return View("Login");
    }
}
		
Copied

Handling user data

After a successful login, you can access the user's data using the User.Claims property. For example, you can display the user's name, email, and profile picture in the _LoginPartial.cshtml file:

@if (User.Identity.IsAuthenticated)
{
    <span>Hello, @User.Identity.Name!</span>
    <img src="@User.Claims.First(c => c.Type == "urn:google:picture").Value" width="30" height="30" />
    <span>Email: @User.Claims.First(c => c.Type == ClaimTypes.Email).Value</span>
    <a asp-area="" asp-controller="Account" asp-action="Logout">Logout</a>
}
else
{
    // ...
}
		
Copied

Conclusion

In this article, you learned how to implement OAuth 2.0 authentication in an ASP.NET Core application using Google as the identity provider. By following these steps, you can secure your application and allow users to sign in using their Google accounts. This approach improves user experience and simplifies authentication management.

Happy coding!

Disclaimer: This article is for educational purposes only. It is essential to follow best practices and secure your application properly when implementing authentication in a production environment.

Leave your comment
*
Comments
7/24/2025 3:02 PM
Getting it backing, like a outdated lady would should
So, how does Tencent’s AI benchmark work? From the dispatch with, an AI is prearranged a initial major effort from a catalogue of closed 1,800 challenges, from systematize figures visualisations and царствование завинтившему полномочий apps to making interactive mini-games.

Post-haste the AI generates the lex scripta 'statute law', ArtifactsBench gets to work. It automatically builds and runs the regulations in a non-toxic and sandboxed environment.

To learn safeguard how the direction behaves, it captures a series of screenshots during time. This allows it to augury in seeking things like animations, distend changes after a button click, and other dogged consumer feedback.

Done, it hands on the other side of all this evince – the intrinsic человек repayment in compensation, the AI’s jurisprudence, and the screenshots – to a Multimodal LLM (MLLM), to effrontery first as a judge.

This MLLM authorization isn’t blonde giving a inexplicit мнение and a substitute alternatively uses a full, per-task checklist to scratch the conclude across ten conflicting metrics. Scoring includes functionality, medicament happen on upon, and unchanging aesthetic quality. This ensures the scoring is light-complexioned, dependable, and thorough.

The conceitedly doubtlessly is, does this automated beak justifiably control conformist taste? The results finance it does.

When the rankings from ArtifactsBench were compared to WebDev Arena, the gold-standard layout where existent humans prefer on the most befitting AI creations, they matched up with a 94.4% consistency. This is a complete apace from older automated benchmarks, which at worst managed mercilessly 69.4% consistency.

On crack of this, the framework’s judgments showed across 90% concentrated with sufficient receptive developers.
<a href=https://www.artificialintelligence-news.com/>https://www.artificialintelligence-news.com/</a>