Create an asp.net core MVC application demonstrating Oauth Google. Write all the codes fully! I want a whole project
Creating a complete ASP.NET Core MVC application that demonstrates OAuth with Google involves several steps. Below, I'll provide a step-by-step guide along with the necessary code snippets to create a simple application.
Open your terminal or command prompt.
Run the following command to create a new MVC project:
dotnet new mvc -n GoogleOAuthDemo
Navigate to the project directory:
cd GoogleOAuthDemo
You need to add the Microsoft.AspNetCore.Authentication.Google
package to your project. Run the following command:
dotnet add package Microsoft.AspNetCore.Authentication.Google
Go to the Google Developer Console.
Create a new project.
Navigate to "Credentials" and click on "Create Credentials" > "OAuth client ID".
Configure the consent screen and set the application type to "Web application".
Add the following redirect URI (replace localhost:5000
with your actual domain if needed):
http://localhost:5000/signin-google
After creating the credentials, note down the Client ID
and Client Secret
.
appsettings.json
Add your Google credentials to the appsettings.json
file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Authentication": {
"Google": {
"ClientId": "YOUR_CLIENT_ID",
"ClientSecret": "YOUR_CLIENT_SECRET"
}
}
}
Startup.cs
Open Startup.cs
and modify the ConfigureServices
and Configure
methods:
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// Configure Google Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Cookies";
options.DefaultSignInScheme = "Cookies";
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie("Cookies")
.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});
}
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 HomeController.cs
in the Controllers
folder:
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 HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[Authorize]
public IActionResult Secret()
{
return View();
}
public IActionResult Login()
{
var redirectUrl = Url.Action("LoginCallback", "Home");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
public async Task<IActionResult> LoginCallback()
{
var result = await HttpContext.AuthenticateAsync("Cookies");
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, result.Principal.FindFirstValue(ClaimTypes.NameIdentifier)),
new Claim(ClaimTypes.Name, result.Principal.FindFirstValue(ClaimTypes.Name))
};
var claimsIdentity = new ClaimsIdentity(claims, "Cookies");
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync("Cookies", claimsPrincipal);
return RedirectToAction("Secret");
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync("Cookies");
return RedirectToAction("Index");
}
}
Home
in the Views
folder.Index.cshtml
:@{
ViewData["Title"] = "Home Page";
}
<h1>Welcome to Google OAuth Demo</h1>
@if (User.Identity.IsAuthenticated)
{
<p>Hello, @User.Identity.Name!</p>
<a asp-controller="Home" asp-action="Logout">Logout</a>
}
else
{
<a asp-controller="Home" asp-action="Login">Login with Google</a>
}
Secret.cshtml
:@{
ViewData["Title"] = "Secret Page";
}
<h1>Secret Page</h1>
<p>You are logged in!</p>
<a asp-controller="Home" asp-action="Logout">Logout</a>
Run the application using the following command:
dotnet run
Open your browser and navigate to https://localhost:5001
(or http://localhost:5000
).
Click on "Login with Google" to authenticate using your Google account.
You now have a simple ASP.NET Core MVC application that demonstrates Google OAuth authentication. You can expand this application by adding more features, such as user roles, profile management, and more. Make sure to replace YOUR_CLIENT_ID
and YOUR_CLIENT_SECRET
in the appsettings.json
file with the actual values from your Google Developer Console.