要将控制器标记为需要授权,通常可以这样装饰它:
[Authorize]
public class MyController : Controller
我们的身份验证是通过第三方提供程序进行的,并且按照设置的方式进行,我们只希望此方法在生产环境中实际生效,例如,我们不希望它在质量检查环境中处于活动状态。在Startup.cs文件中关闭环境很容易,但是有没有办法有条件地装饰控制器?我开始研究政策和角色,看来它可能被黑了,但是有更好的方法吗?
答案 0 :(得分:2)
如果您使用的是Asp.NET Core,请按照此处的文档进行操作:
https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1 https://docs.microsoft.com/en-us/aspnet/core/security/authorization/dependencyinjection?view=aspnetcore-2.1
您可以像这样制定自定义策略:
public class EnvironmentAuthorize : IAuthorizationRequirement
{
public string Environment { get; set; }
public EnvironmentAuthorize(string env)
{
Environment = env;
}
}
public class EnvironmentAuthorizeHandler : AuthorizationHandler<EnvironmentAuthorize>
{
private readonly IHostingEnvironment envionment;
public EnvironmentAuthorizeHandler(IHostingEnvironment env)
{
envionment = env;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EnvironmentAuthorize requirement)
{
if (requirement.Environment != envionment.EnvironmentName)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
在Startup.cs中:
services.AddAuthorization(options =>
{
options.AddPolicy("ProductionOnly", policy =>
policy.Requirements.Add(new EnvironmentAuthorize("Production")));
});
services.AddSingleton<IAuthorizationHandler, EnvironmentAuthorizeHandler>();
在控制器中:
[Authorize(Policy = "ProductionOnly")]
public class MyController : Controller
尽管有可能,但我不推荐这样做,确实是一场噩梦。