简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM