Create an asp.net core MVC application demonstrating Oauth Google
Creating an ASP.NET Core MVC application that uses OAuth with Google for authentication involves several steps. Below is a step-by-step guide to help you set up the application.
GoogleOAuthDemo
) and click "Create".https://localhost:5001/signin-google
(Adjust the port if necessary based on your project settings.)Client ID
and Client Secret
.Open the Package Manager Console and run the following command to install the necessary packages:
Install-Package Microsoft.AspNetCore.Authentication.Google
Startup.cs
Open Startup.cs
and modify the ConfigureServices
and Configure
methods as follows:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// Configure Google Authentication
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
options.ClientId = "YOUR_CLIENT_ID"; // Replace with your Client ID
options.ClientSecret = "YOUR_CLIENT_SECRET"; // Replace with your Client Secret
});
}
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(); // Enable authentication
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Create a new controller named AccountController.cs
:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login(string returnUrl = "/")
{
var redirectUrl = Url.Action("GoogleResponse", "Account", new { returnUrl });
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[HttpGet]
public async Task<IActionResult> GoogleResponse(string returnUrl = "/")
{
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (result?.Principal != null)
{
var claimsIdentity = (ClaimsIdentity)result.Principal.Identity;
// You can add additional claims here if needed
// claimsIdentity.AddClaim(new Claim("CustomClaim", "value"));
}
return LocalRedirect(returnUrl);
}
[HttpGet]
[Authorize]
public IActionResult Logout()
{
return SignOut(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
Views/Shared/_Layout.cshtml
and add links for login and logout:<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<form asp-controller="Account" asp-action="Logout" method="post" class="form-inline">
<button type="submit" class="btn btn-link nav-link">Logout</button>
</form>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link" asp-controller="Account" asp-action="Login">Login with Google</a>
</li>
}
</ul>
You have successfully created an ASP.NET Core MVC application that uses Google OAuth for authentication. You can further customize the application by adding user roles, storing user information in a database, and enhancing the UI.