Authentication verifies the identity of a user, ensuring they are who they claim to be.
Authorization determines what resources the authenticated user is allowed to access.
They are essential for securing web applications, protecting sensitive data, and managing user access control effectively.
Follow these steps:
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services for authentication
builder.Services.AddAuthentication("CookieAuth")
.AddCookie("CookieAuth", options =>
{
options.LoginPath = "/Account/Login";
});
var app = builder.Build();
// Use authentication middleware
app.UseAuthentication();
app.UseAuthorization();
app.Run();
The AddAuthentication
method configures cookie-based authentication. The LoginPath
specifies the login URL.
// Pages/Account/Login.cshtml.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
public class LoginModel : PageModel
{
public IActionResult OnPost(string username, string password)
{
if (username == "admin" && password == "password")
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Admin")
};
var identity = new ClaimsIdentity(claims, "CookieAuth");
var principal = new ClaimsPrincipal(identity);
HttpContext.SignInAsync("CookieAuth", principal);
return RedirectToPage("/Index");
}
return Page();
}
}
The OnPost
method authenticates the user and creates claims for identity.
// Pages/Admin.cshtml
@page
@attribute [Authorize(Roles = "Admin")]
Welcome, Admin!
The [Authorize]
attribute restricts access based on roles.
// Pages/Account/Logout.cshtml.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class LogoutModel : PageModel
{
public IActionResult OnGet()
{
HttpContext.SignOutAsync("CookieAuth");
return RedirectToPage("/Index");
}
}
The OnGet
method signs out the user and redirects them to the homepage.
// Program.cs
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
The AddAuthorization
method allows for creating custom authorization policies.