问题
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