Authentication vs authorisation

Authentication asks who you are. Authorisation asks what you may do. Mixing them up causes real breaches.

Time O(1)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Login (authentication) proves identity once and gives the browser a session cookie or token. Every later request is then checked against what that identity is allowed to do (authorisation). 401 means "we don’t know who you are"; 403 means "we know, and the answer is no".

Code

app.MapPost("/login", (Login l, Users u, HttpContext ctx) =>
{
    var user = u.Verify(l.Email, l.Password);   // hash compare
    if (user is null) return Results.Unauthorized();
    ctx.SignInAsync(user.ToPrincipal());        // session cookie
    return Results.Ok();
});
app.MapDelete("/admin/users/{id}", DeleteUser)
   .RequireAuthorization(p => p.RequireRole("Admin"));
// signed in but not Admin -> 403 Forbidden

Tips

In the .NET library

ASP.NET Core separates UseAuthentication (who) from UseAuthorization (what), and policies with RequireRole or custom requirements express the rules.