Creating ASP.NET Core MVC App with Google OAuth

Answered using OpenAI o1 mini by OpenAI o1

Question:

Create an asp.net core MVC application demonstrating Oauth Google

Answer:

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.

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

  1. Open Visual Studio (or your preferred IDE).
  2. Create a new project.
  3. Select "ASP.NET Core Web Application" and click "Next".
  4. Name your project (e.g., GoogleOAuthDemo) and click "Create".
  5. Choose "Web Application (Model-View-Controller)" and ensure that "Authentication" is set to "No Authentication". Click "Create".

Step 2: Register Your Application with Google

  1. Go to the Google Developer Console.
  2. Create a new project.
  3. Navigate to "Credentials" in the left sidebar.
  4. Click on "Create Credentials" and select "OAuth client ID".
  5. Configure the consent screen by providing the necessary information.
  6. For "Application type", select "Web application".
  7. Add the following to the "Authorized redirect URIs":
    https://localhost:5001/signin-google
    
    (Adjust the port if necessary based on your project settings.)
  8. Click "Create" and note down the Client ID and Client Secret.

Step 3: Install Required NuGet Packages

Open the Package Manager Console and run the following command to install the necessary packages:

Install-Package Microsoft.AspNetCore.Authentication.Google

Step 4: Configure Google Authentication in 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?}");
        });
    }
}

Step 5: Create a Controller for Authentication

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

Step 6: Update the Views

  1. Open 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>

Step 7: Run the Application

  1. Build and run your application.
  2. Navigate to the home page and click on "Login with Google".
  3. You should be redirected to the Google login page. After logging in, you will be redirected back to your application.

Conclusion

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.