Complete ASP.NET Core MVC Google OAuth App

Answered using OpenAI o1 mini by OpenAI o1

Question:

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

Answer:

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.

Prerequisites

  1. .NET SDK: Make sure you have the .NET SDK installed on your machine.
  2. Google Developer Console: You need to create a project in the Google Developer Console and obtain OAuth 2.0 credentials.

Step 1: Create a New ASP.NET Core MVC Project

You can create a new ASP.NET Core MVC project using the command line:

dotnet new mvc -n GoogleOAuthDemo
cd GoogleOAuthDemo

Step 2: Install Required NuGet Packages

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

Step 3: Configure Google OAuth

  1. Go to the Google Developer Console.
  2. Create a new project.
  3. Navigate to "Credentials" and create OAuth 2.0 credentials.
  4. Set the redirect URI to https://localhost:5001/signin-google (or your local URL).
  5. Note the Client ID and Client Secret.

Step 4: Update 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"
    }
  }
}

Step 5: Configure Services in 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?}");
        });
    }
}

Step 6: Create the Home Controller

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");
    }
}

Step 7: Create Views

Create the following views in the Views/Home folder:

  1. Index.cshtml:
@{
    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>
  1. Profile.cshtml:
@{
    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>

Step 8: Run the Application

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.

Conclusion

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.