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.
OIDC and OAuth simplify user management by offloading authentication and authorization to external providers, ensuring secure and scalable implementations.
Follow these steps:
// Run the following command:
Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect
This package provides OIDC authentication support.
// 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.
// Pages/Protected.cshtml
@page
@attribute [Authorize]
Protected Content
This page requires authentication.
Add the [Authorize]
attribute to protect pages or endpoints.
// 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.
// 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.
// 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.