Advertisement
Intermediate ASP.NET Core, Authorization

What is the difference between AuthorizeAttribute's behavior returning 401 versus 403, and what determines which one a client receives?

Short answer

A 401 Unauthorized response means the request lacks valid authentication credentials entirely (or they failed to validate) -- the user isn't recognized at all.

Save ASP.NET Core mock interview
Advertisement
AModel answer
A 401 Unauthorized response means the request lacks valid authentication credentials entirely (or they failed to validate) -- the user isn't recognized at all. A 403 Forbidden means the user IS successfully authenticated but lacks sufficient permissions for the specific requested action -- ASP.NET Core's authorization middleware automatically returns the correct one based on whether HttpContext.User.Identity.IsAuthenticated is true or false when an authorization check fails.
// Unauthenticated request to a protected endpoint -> 401
// GET /api/admin/users (no Authorization header at all)

// Authenticated but insufficiently privileged request -> 403
// GET /api/admin/users
// Authorization: Bearer <valid token for a non-admin user>
Real-world example
A frontend application distinguishes between a 401 (redirect to login page, since the session may have expired) and a 403 (show a permanent 'access denied' message, since re-authenticating wouldn't help) based on this status code difference.
Likely follow-ups
  • Can you customize what triggers 401 versus 403 beyond the default authenticated/unauthenticated distinction?
  • How should a client's UI handle each status code differently?
Related topics