ASP.NET Core Web App(模型-视图-控制器)中的站点级[授权]

问题描述 投票:0回答:1

我正在编写小型内部网络应用程序(决定第一次尝试 asp.net)。这个应用程序没有公共页面,所以我需要锁定每个页面。

首先,我开始在每个控制器的每个方法中编写这段代码:

if (User.Identity is { IsAuthenticaed: true }) 
{
  // Do task
} else {
  throw new Exception("Unauthorized")
}

但后来我发现

[Authorize]
。现在我只是将它写在每个控制器之上!但还是很手动,有没有办法锁定整个网站?

asp.net-mvc asp.net-core asp.net-identity
1个回答
0
投票

如果我需要做一次,我可以。我怎样才能做到这一点?还有,会不会 重定向到登录页面,如[授权]

您可以为所有控制器、操作和 Razor 页面全局创建一个过滤器,创建一个 AuthorizeFilter:

尝试添加以下代码:

 // Configure the custom policy
    var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .RequireRole("Admin", "SuperUser")
            .Build();
 // Pass a policy in the constructor of the Authorization filter
    builder.Services.AddControllersWithViews(options =>
    {
        options.Filters.Add(new AuthorizeFilter(policy));
    });

请记住,此政策适用于全球,因此您需要确保您的“Login”和“AccessDenied”页面用

[AllowAnonymous]
装饰,否则您最终会遇到无休止的重定向。

© www.soinside.com 2019 - 2024. All rights reserved.