[英]How to deny anonymous users in asp.net core razor pages?
How would I deny anonymous users to access any of the razor pages in asp.net core other then a login page? 我如何拒绝匿名用户访问asp.net核心中除登录页面以外的任何剃刀页面?
I tried 我试过了
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.RootDirectory = "/";
options.Conventions.AllowAnonymousToPage("/Account/Login");
options.Conventions.AuthorizeFolder("/");
})
.SetCompatibilityVersion(CompatibilityVersion.Latest);
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 或者您可以创建一个basecontroller类
[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
也在这里,
GlobalFilters
//listed answer
GlobalFilters.Filters.Add(new AuthorizeAttribute() { Roles = "Admin, SuperUser" });
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: 对于Razor Pages 2.x应用程序,您需要做的就是将以下内容添加到
Configure
方法中,以防止未经授权的用户访问Pages文件夹或子文件夹中的任何页面:
services.AddMvc().AddRazorPagesOptions(options => {
options.Conventions.AuthorizeFolder("/");
});
If you are using .NET Core 3, the following will do the same thing: 如果您使用的是.NET Core 3,则以下操作将执行相同的操作:
services.AddRazorPages(options => {
options.Conventions.AuthorizeFolder("/");
});
The unauthorised user will be redirected to the default login page, which is at Identity/Account/Login
未经授权的用户将被重定向到默认登录页面,该页面位于
Identity/Account/Login
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.