Authentication and Authorization in .NET Core

What are Authentication and Authorization?

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.

  • Authentication Example: Logging in with a username and password.
  • Authorization Example: Accessing admin-only pages based on user roles.

Why Use Authentication and Authorization?

They are essential for securing web applications, protecting sensitive data, and managing user access control effectively.


How to Implement Authentication and Authorization in .NET Core

Follow these steps:

1. Add Authentication Middleware


// 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.

2. Create a Login Page


// 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.

3. Protect Pages with Authorization


// Pages/Admin.cshtml
@page
@attribute [Authorize(Roles = "Admin")]

Welcome, Admin!

The [Authorize] attribute restricts access based on roles.

4. Configure Logout


// 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.

5. Add Authorization Policies (Optional)


// Program.cs
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});

                

The AddAuthorization method allows for creating custom authorization policies.