【发布时间】:2020-06-18 08:22:11
【问题描述】:
默认情况下,网站只能匿名访问。
管理员有一个按钮可以将站点切换到维护模式,该按钮应该使用内置的 CookieAuthentication 启用授权(在数据库中翻转一点,与本文无关)。
为了让它工作,我首先配置了 cookie 身份验证(在 startup.cs 中):
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.LoginPath = new PathString("/auth/login");
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
}
然后在相关的控制器上,我放了一个[Authorize]属性。
[Authorize]
public class HomeController : Controller
{
//removed
}
这非常有效——当授权属性存在时,cookie auth 就会启动。到目前为止一切顺利。
现在我想在维护模式关闭时禁用授权运行时。
尝试的解决方案
这是我经过大量反复试验和研究后得出的结论。
public void OnAuthorization(AuthorizationFilterContext context)
{
IMaintenanceModeDataService ds = context.HttpContext.RequestServices.GetService<IMaintenanceModeDataService>();
if (!ds.IsMaintenanceModeEnabled)
{
//Maintenance mode is off, no need for authorization
return;
}
else
{
ClaimsPrincipal user = context.HttpContext.User;
if (user.Identity.IsAuthenticated)
{
//when the user is authenticated, we don't need to do anything else.
return;
}
else
{
//we're in maintenance mode AND the user is not
//It is outside the scope of this to redirect to a login
//We just want to display maintenancemode.html
context.Result = new RedirectResult("/maintenancemode.html");
return;
}
}
}
[MaintenanceModeAwareAuthorize]
public class HomeController : Controller
{
//removed
}
这在站点处于维护模式时非常有用。
当站点未处于维护模式时,cookie 身份验证仍会启动并需要身份验证。我可以删除它并尝试实现我自己的身份验证,但是当我们已经内置了精心设计的解决方案时,那将是愚蠢的。
当站点未处于维护模式(运行时)时,如何禁用授权?
注意事项:
问:为什么不通过执行 x 来处理这个问题(这需要服务器端访问配置、环境变量、服务器或类似内容)?
答:因为非技术管理员用户需要通过单击后端中的按钮立即访问它。
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.2