11 November 2026

ASP.NET Core Authentication and Authorization for Beginners

  Asp.Net CS By Example       11 November 2026

Security fundamentals

Authentication answers “Who are you?” Authorization answers “What are you allowed to do?” This lesson uses a development-friendly cookie scheme to demonstrate the pipeline. It is not a complete production login system.

1. Create the project

dotnet new web -n SecureApi
cd SecureApi

2. Configure a cookie scheme and policy

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => options.LoginPath = "/login");
builder.Services.AddAuthorization(options =>
    options.AddPolicy("StudentsOnly", policy =>
        policy.RequireClaim("role", "student")));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/public", () => "Anyone can read this.");
app.MapGet("/student-area", () => "Student area")
   .RequireAuthorization("StudentsOnly");
app.Run();

3. Read the request pipeline

UseAuthentication identifies the caller and sets HttpContext.User. UseAuthorization evaluates the policy. Put authentication before authorization. Without a valid identity, the protected endpoint returns an authorization challenge.

Important production note

Do not invent your own password storage. Use ASP.NET Core Identity or a trusted external identity provider, require HTTPS, protect secrets, configure cookie settings and review Microsoft security guidance before deployment.

Practice

Create a second policy named TeachersOnly. Add a public help endpoint and a protected endpoint that requires it.

Self-check

Authentication is identity; authorization is permission. A policy is a reusable rule. Middleware order controls whether the user is known before access is checked.

Return to the .NET Core learning path · Official authentication overview · Authorization overview

logoblog

Thanks for reading ASP.NET Core Authentication and Authorization for Beginners

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.