Search code examples
c#asp.netasp.net-core-mvcrazor-pagesasp.net-authorization

Difference between Authorize attribute and AuthorizePage(string) method


I am wondering if is there any difference of [Authorize] attribute and AuthorizePage(string) method in ASP.NET Core? Project uses ASP.NET Core 3.1. Is there any advantage or disadvantage using one?

As I know well, the two codes below make the same thing:

Using [Authorize] attribute

// ...
namespace MyApp.Account.Manage
{
    [Authorize]
    public partial class IndexModel : PageModel
    {
// ...

Using AuthorizePage(string) method in Startup.ConfigureServices

services.AddMvc()
  .AddMvcOptions(o => o.EnableEndpointRouting = false)
  .AddRazorPagesOptions(options =>
  {
     options.Conventions.AuthorizePage("Account/Manage");
  });

Solution

  • You are right, both the [Authorize] attribute and AuthorizePage() are set authorization for the specified page.

    Using the [Authorize] attribute.

    The Authorize attribute used in the Role-Based Authorization, it enables you to restrict access to resources based on roles. It is a declarative attribute that can be applied to a controller or an action method or Razor page. If you specify this attribute without any arguments, it only checks if the user is authenticated.

    By the Authorize attribute, when user access the specified controller or action method or Razor page, it will check whether current user has permission to access it.

    Using the AddRazorPagesOptions method and AuthorizePage() method.

    Asp.net core provides one way to control access in your Razor Pages app is to use authorization conventions at startup. By using this way, we could use the AddRazorPagesOptions method to add the conventions to the pages, such as use the AuthorizePage method to add authorization to the specified page (same with the Authorize attribute).

    But by using the authorization conventions method, it provides related methods to add authorization to a folder of pages, an area page or a folder of areas.

    Summary, if you just want to set authorization for the specified page, you could use each of them. But, if you want to set authorization for multiple pages, it is better to use the authorization conventions method. More details information, check the Razor Pages authorization conventions in ASP.NET Core.