Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.0 - Razor - Authorize

I'm trying out asp.net core 2 razor pages. If someone tries to access a page and they are not logged in or are in the correct role, I should not give them access to that page.

what is the appropriate way to limit the person's access to the page?

I would think that I would put some type of an attribute in the page's view model class, but that does not seem to work. I've tried to add attributes to the various methods and the class with no luck.

like image 912
Wallace B. McClure Avatar asked Jan 31 '26 05:01

Wallace B. McClure


1 Answers

To use the authorize attribute you can decorate the PageModel with the AuthorizeAttribute.

For example:

// using Microsoft.AspNetCore.Authorization

[Authorize]
public class IndexModel : PageModel
{
    ...
} 

Alternatively, you can also setup authorization under the options of the ConfigureServices method:

services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AuthorizeFolder("/MembersOnly");
        options.Conventions.AuthorizePage("/Account/Logout");

        options.Conventions.AuthorizeFolder("/Pages/Admin", "Admins"); // with policy
        options.Conventions.AllowAnonymousToPage("/Pages/Admin/Login"); // excluded page

        options.Conventions.AllowAnonymousToFolder("/Public"); // just for completeness
    });

The AuthorizeFolder will restrict access to the entire folder, whereas the AuthorizePage would be restricting access based on the individual page. The AllowAnonymousToFolder and AllowAnonymousToPage doing the opposite, accordingly.

For specific documentation on the above, as of today, the documentation is still being completed. However, you can read about the progress of it and track it here https://github.com/aspnet/Docs/issues/4281

Otherwise, you can have a more general read about Authorization in ASP.NET Core on the official Microsoft Docs.

like image 120
Svek Avatar answered Feb 02 '26 19:02

Svek