How to add authorization to RazorPages?

回眸只為那壹抹淺笑 提交于 2019-12-24 23:13:55

问题


I have looked at the current official Microsoft Docs and was unable to find anything properly covering how to handle authorization for RazorPages.

I figured out that you can add the AuthorizeAttribute to the PageModel like so:

// using Microsoft.AspNetCore.Authorization

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

I don't want to repeat this for every page. Is there a better way?


回答1:


You can configure authorization under the ConfigureServices method. Here is an example :

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 example above is extended from an example provided in the official repository.

The AuthrorizeFolder 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



来源:https://stackoverflow.com/questions/46881926/how-to-add-authorization-to-razorpages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!