ASP.NET Core OpenID Connect and OAuth Integration

What is OpenID Connect and OAuth?

OpenID Connect (OIDC) is an authentication protocol built on top of the OAuth 2.0 framework. OAuth provides secure delegated access, allowing applications to access user resources on their behalf, while OpenID Connect adds user authentication and identity management.

  • Secure Authentication: Validates the user’s identity through trusted providers.
  • Single Sign-On (SSO): Users can log in with one account across multiple applications.
  • Flexible Integration: Works with external identity providers like Google, Microsoft, and Facebook.

Why Use OpenID Connect and OAuth?

OIDC and OAuth simplify user management by offloading authentication and authorization to external providers, ensuring secure and scalable implementations.


How to Implement OpenID Connect and OAuth in ASP.NET Core

Follow these steps:

1. Install Required NuGet Packages


// Run the following command:
Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect

                

This package provides OIDC authentication support.

2. Register Authentication Services


// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add OpenID Connect authentication
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = "https://login.microsoftonline.com/common"; // Replace with your provider's authority
    options.ClientId = "Your-Client-Id";
    options.ClientSecret = "Your-Client-Secret";
    options.ResponseType = "code";
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
    options.SaveTokens = true;
});

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.Run();

                

Configure your application's authority, client ID, and secret from your provider's settings.

3. Secure Routes with Authentication


// Pages/Protected.cshtml
@page
@attribute [Authorize]

Protected Content

This page requires authentication.

Add the [Authorize] attribute to protect pages or endpoints.

4. Configure Redirect URIs


// In appsettings.json or provider configuration portal:
{
  "Authentication": {
    "RedirectUri": "https://localhost:5001/signin-oidc",
    "PostLogoutRedirectUri": "https://localhost:5001/signout-callback-oidc"
  }
}

                

Ensure these URIs are registered with your identity provider.

5. Handle Logout


// Add logout endpoint in Program.cs
app.MapGet("/logout", async context =>
{
    await context.SignOutAsync("Cookies");
    await context.SignOutAsync("oidc");
    context.Response.Redirect("/");
});

                

Log out users from both the application and identity provider.

6. Access User Information


// Pages/Profile.cshtml.cs
@page
@attribute [Authorize]

using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;

public class ProfileModel : PageModel
{
    public string UserName { get; private set; }
    public string Email { get; private set; }

    public void OnGet()
    {
        var claims = User.Identity as ClaimsIdentity;
        UserName = claims?.FindFirst("name")?.Value;
        Email = claims?.FindFirst(ClaimTypes.Email)?.Value;
    }
}

                

Retrieve user information from claims provided by the identity provider.