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);
Click on your virtual directory under the IIS you have Authentication click on it and there you will be able to see Anonymous authentication disable it.
Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.
In MVC you normally use the [Authorize] attribute to manage authorization. Controllers or individual actions that are dressed with that attribute will require that the user is authorized in order to access them - all other actions will be available to anonymous users.
In ASP.NET MVC, by default, all the action methods are accessible to both anonymous and authenticated users. But, if you want the action methods to be available only for authenticated and authorized users, then you need to use the AuthorizationFilter in MVC.
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
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" });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With