有一个 ASP.NET Core 站点,想让所有 Controller 登录后才能访问,但不想每个 Controller 加 [Authorize]
,请问最简单的实现方法是什么?
在博文 Globally Require Authenticated Users By Default Using Fallback Policies in ASP.NET Core 中找到了完美答案:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
}
}
今天在同事的代码中发现一个更简单的解决方法
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
}
@dudu:
MapAreaControllerRoute 后面的 RequireAuthorization 不起作用,有没有什么办法
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(name: "areas", "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}").RequireAuthorization();
endpoints.MapDefaultControllerRoute().RequireAuthorization();
});
@奶茶爽歪歪: 试试 options.FallbackPolicy
@dudu: Thanks 有作用了.
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});