ASP.NET Core MVC Intermediate

Authorization with the [Authorize] attribute

Once you know who the user is, authorization decides what they may do. This lesson covers the [Authorize] and [AllowAnonymous] attributes, what happens when access is denied, and how to require sign-in for the whole app by default.

What happens on a protected page
  1. StartRequest for /ordersOrdersController has [Authorize]
  2. Step 2Authentication runsThe cookie is read and User is set (or left anonymous)
  3. Step 3Authorization checksIs the user signed in and allowed?
  4. Step 4Not signed inChallenge: redirect to the login page with a returnUrl
  5. Step 5Signed in but not allowedForbid: 403, shown as the access denied page
  6. EndAllowedThe action runs normally

The idea in plain words

Put [Authorize] on a controller or action and only signed-in users can reach it. Put [AllowAnonymous] on an action inside such a controller to open it up again, for example a login page. When an anonymous user hits a protected page, the cookie authentication handler redirects them to the login page and brings them back afterwards.

Authorization uses the User object built by authentication, so UseAuthentication must come before UseAuthorization in Program.cs.

Example

C#
[Authorize]                       // every action needs a signed-in user
public class OrdersController : Controller
{
    public IActionResult Index()
    {
        var name = User.Identity?.Name;   // the signed-in user's name
        return View();
    }

    [AllowAnonymous]               // except this one
    public IActionResult TrackPublic(string code) => View();
}

Secure by default

Instead of remembering [Authorize] on every controller, require an authenticated user everywhere with a fallback policy and mark public pages with [AllowAnonymous].

C#
builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

Common mistakes

  • Hiding a link in the view but leaving the action unprotected. Always protect the action itself.
  • Placing [AllowAnonymous] on a controller, which overrides every [Authorize] inside it.
  • Checking permissions only in JavaScript.
  • Forgetting that a fallback policy also applies to static files served after authorization middleware.

Interview question

What is the difference between a challenge and a forbid result in ASP.NET Core authorization?

A challenge is returned when the user is not authenticated: the authentication handler asks them to sign in, which for cookie authentication means a redirect to the login page (or a 401 for APIs). A forbid is returned when the user is authenticated but fails the authorization requirements: the handler returns 403 or redirects to the access denied page.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.