Course contentsShow
← C#
Lesson 1210 of 1,90811. Identity, Security, and ClaimsFree lesson

Authorization Filters and Middleware

Implement global authorization filters to enforce security boundaries across controllers.

In this lesson, you will learn how to enforce security boundaries across your entire application using global authorization filters and middleware, ensuring no endpoint is left unprotected by mistake.

The Problem: The "Default Allow" Trap

When building large APIs, it is easy to forget to add the [Authorize] attribute to a new controller. If you rely solely on per-controller attributes, you inevitably create "security holes" where sensitive data is exposed accidentally. Global authorization solves this by switching your security posture to "Default Deny."

Implementing Global Authorization Filters

In ASP.NET Core, you can apply authorization requirements globally during your service registration in Program.cs. By adding an AuthorizeFilter to the MvcOptions, you force every single controller action to require authentication by default.

builder.Services.AddControllers(options =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
});

Once this is configured, every action in your application is protected. If you have public endpoints, you simply mark them with the [AllowAnonymous] attribute to "opt-out" of the global requirement.

Middleware vs. Filters

It is important to distinguish where these checks occur. Authorization Middleware runs as part of the request pipeline, usually placed after UseAuthentication(). It checks if the request is valid before it even reaches the MVC routing system.

Authorization Filters, conversely, are part of the MVC pipeline. They are specifically designed to inspect the controller and action metadata. While middleware is great for global security checks (like validating a custom header or a global API key), filters are much better suited for application-level logic because they have access to the ActionDescriptor, allowing you to easily handle exceptions or specific routing requirements that middleware might find difficult to parse.

By combining these, you create a "defense-in-depth" strategy: Middleware provides a perimeter fence, and Global Filters provide the internal room-by-room security policy.

Key Takeaway: Use global authorization filters to enforce a "secure by default" architecture, requiring you to explicitly opt-in to public access rather than remembering to opt-in to security.