The ASP.NET Core Authorize attribute restricts an endpoint to authenticated users or users meeting a specified authorization policy. Apply it to controller and Razor Page classes, individual action or handler methods, or a Blazor entry-point page; class-level application protects every method in that class. section 11.3 section 39.3.1
Choose the restriction that matches the application:
- Use [Authorize] without arguments to allow any authenticated user. section 11.3 section 39.3.1
- Use Roles="Admins" or a comma-separated role list to restrict access further. section 39.3.1
- Put the attribute on a shared page-model base class when many administration pages require the same policy; use [AllowAnonymous] on exceptional controller actions. section 39.3.1
- Protect a web service controller with [Authorize]; an unauthenticated JavaScript client receives a 401 Unauthorized response. section 39.5.2
Role-restricted administration pages
A shared AdminPageModel can carry [Authorize(Roles="Admins")], causing every Razor Page that derives from it to require membership in the Admins role. section 39.3.1
Listing 39.9 Applying an attribute in the AdminPageModel.cs file in the Pages folder in the Advanced project
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Authorization;
namespace Advanced.Pages {
[Authorize(Roles="Admins")]
public class AdminPageModel : PageModel {
}
}
Inspect the complete base page-model declaration, including the Microsoft.AspNetCore.Authorization import and role-restricted attribute. section 39.3.1
Authentication state determines the result: an unauthenticated browser is redirected to the login path, while an authenticated user without authorization is sent to the access-denied path. Cookie options can replace both defaults. Applying the attribute to a Blazor host page protects the application entry point as well. section 39.3.5 section 39.4


