5
votes

How would I deny anonymous users to access any of the razor pages in asp.net core other then a login page?

I tried

    services.AddMvc()
        .AddRazorPagesOptions(options =>
        {
            options.RootDirectory = "/";
            options.Conventions.AllowAnonymousToPage("/Account/Login");
            options.Conventions.AuthorizeFolder("/");
        })
        .SetCompatibilityVersion(CompatibilityVersion.Latest);
2

2 Answers

6
votes

For a Razor Pages 2.x application, all you need to do is add the following to your Configure method to prevent unauthorised users accessing any page in the Pages folder or subfolders:

services.AddMvc().AddRazorPagesOptions(options => {
    options.Conventions.AuthorizeFolder("/");
});

If you are using .NET Core 3, the following will do the same thing:

services.AddRazorPages(options => {
    options.Conventions.AuthorizeFolder("/");
});

The unauthorised user will be redirected to the default login page, which is at Identity/Account/Login

3
votes

add attributes in controllers

[Authorize]
public class HomeController : Controller 

then in endpoints you want to access anonymously

[AllowAnonymous] 
public ViewResult Index() 
{ 
      return View(); 
}  

or you could create a basecontroller class

[Authorize]
public class BaseController : Controller 
{
    ...
}

then inherit it

public class HomeController : BaseController

or as listed in this documentation

//sample code
services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AuthorizePage("/Contact");
        options.Conventions.AuthorizeFolder("/Private");
        options.Conventions.AllowAnonymousToPage("/Private/PublicPage");
        options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
    })

also here, GlobalFilters

//listed answer
GlobalFilters.Filters.Add(new AuthorizeAttribute() { Roles = "Admin, SuperUser" });