ASP.NET Core MVC Interview Question #114

What is the difference between Challenge, Forbid, and Unauthorized?

Authentication, Authorization, Security & State Management Mid-Level Intermediate

Quick Interview Answer

Challenge asks the configured authentication system to handle an unauthenticated request, which may redirect a cookie-authenticated browser to a login page. Forbid indicates that the user is authenticated but is not permitted to access the resource.

Detailed Explanation

Challenge asks the configured authentication system to handle an unauthenticated request, which may redirect a cookie-authenticated browser to a login page. Forbid indicates that the user is authenticated but is not permitted to access the resource.

Unauthorized produces an HTTP 401 result directly. In browser-based cookie authentication, Challenge is often more appropriate when the intended behavior is to invoke the authentication handler.

Code Example

if (User.Identity?.IsAuthenticated != true)
    return Challenge();

if (!User.IsInRole("Admin"))
    return Forbid();