In asp.net core it is very easy to define the razor pages authorization for pages and folders as follows:
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Contact");
options.Conventions.AuthorizeFolder("/Private");
options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
});
My problem is that I want to use roles in my project but I can not find a way to define which roles are allowed to view the contents of the page.
I tried to use the Authorize attribute but it does not work with Razor Pages.
The AuthorizePage can take a second parameter which can be used in order to define the policy which will be used in order to determine if the current use can see the specified page or not. I used it as follows:
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin"));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Index", "RequireAdministratorRole");
});
The problem is that it still does noe work. It acts like I have not defined the policy. When I am logged I can see the page and when I am not logged it redirects me to the loggin form.
Is something else that I have to do in order to make it work?
app.UseAuthentication();
– Leaseholder