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
- Visual Studio or Visual Studio Code with the .NET workload installed.
- A Google Cloud Platform (GCP) project with OAuth 2.0 client ID credentials for a web application.
- 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
Configuring Google as an external login provider
- 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"
}
}
- In the
Startup.cs
file, add the Google authentication services in theConfigureServices
method:
services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
options.CallbackPath = Configuration["Authentication:Google:CallbackPath"];
});
- Configure the authentication middleware in the
Configure
method:
app.UseAuthentication();
app.UseAuthorization();
- In the
Startup.cs
file, add the Google authentication services in theConfigureServices
method:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Adding Google login to your application
- 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>
}
- Add an
ExternalLogin
action in theAccountController.cs
file:
[HttpPost]
public IActionResult ExternalLogin(string provider)
{
var redirectUrl = Url.Action("ExternalLoginCallback", "Account");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
- 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");
}
}
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
{
// ...
}
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.