默认情况下,网站仅是匿名访问。
管理员具有将站点切换到维护模式的按钮,该按钮应使用内置的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
}
这非常好-当存在authorize-attribute时,将启动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(需要服务器端访问config,环境vars,服务器或类似的东西)来解决这个问题?
A:因为非技术管理员用户需要通过单击后端中的按钮来立即访问它。
[AllowAnonymous]
的单独控制器中具有未授权的动作。 if (!user.IsMaintenanceModeEnabled)
{
context.Result = new RedirectResult("Another controller with [AllowAnonymous]");
return;
}