Create an asp.net core MVC application demonstrating Oauth Google. Write all the codes fully! I want a whole project write all the codes for views and controllers and everything
Creating a complete ASP.NET Core MVC application that demonstrates OAuth with Google involves several steps. Below, I will provide a simplified version of such an application, including the necessary code for the project.
You can create a new ASP.NET Core MVC project using the command line:
dotnet new mvc -n GoogleOAuthDemo
cd GoogleOAuthDemo
You need to install the Microsoft.AspNetCore.Authentication.Google
package. You can do this via the command line:
dotnet add package Microsoft.AspNetCore.Authentication.Google
https://localhost:5001/signin-google
(or your local URL).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
Update the Startup.cs
file to configure authentication:
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();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "Google";
})
.AddCookie("Cookies")
.AddGoogle("Google", options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
options.Scope.Add("email");
options.Scope.Add("profile");
options.SaveTokens = true;
});
}
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();
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 Profile()
{
var claimsIdentity = User.Identity as ClaimsIdentity;
var email = claimsIdentity.FindFirst(ClaimTypes.Email)?.Value;
var name = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
ViewBag.Email = email;
ViewBag.Name = name;
return View();
}
public IActionResult Login()
{
var redirectUrl = Url.Action("Index", "Home");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[Authorize]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index");
}
}
Create the following views in the Views/Home
folder:
@{
ViewData["Title"] = "Home Page";
}
<h1>Welcome to Google OAuth Demo</h1>
<p>
@if (User.Identity.IsAuthenticated)
{
<a asp-controller="Home" asp-action="Profile">Profile</a>
<form asp-controller="Home" asp-action="Logout" method="post">
<button type="submit">Logout</button>
</form>
}
else
{
<a asp-controller="Home" asp-action="Login">Login with Google</a>
}
</p>
@{
ViewData["Title"] = "Profile";
}
<h1>User Profile</h1>
<p>Name: @ViewBag.Name</p>
<p>Email: @ViewBag.Email</p>
<a asp-controller="Home" asp-action="Index">Back to Home</a>
Now you can run your application:
dotnet run
Navigate to https://localhost:5001
in your browser. You should see the home page with a link to log in with Google. After logging in, you will be redirected to the profile page displaying your name and email.
This is a basic example of how to implement Google OAuth in an ASP.NET Core MVC application. You can expand upon this by adding more features, error handling, and styling as needed.