c# - Environment dependent controller with [Authorize]
问题描述
To mark a controller as requiring authorization you typically decorate it like this:
[Authorize]
public class MyController : Controller
Our auth is through a 3rd party provider and given the way it is setup, we only want this to actually be in effect in our production environment, we don't want it to be active in QA environment for example. It's easy to toggle off environment in the Startup.cs file but is there a way to conditionally decorate the controllers? I started looking at policies and roles and that seem like it might be hacked to work but is there a better way?
解决方案
如果您使用的是 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;
}
}
在 de 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
虽然有可能,但我不推荐这样做,在不同的环境中有不同的行为确实是一场噩梦。
推荐阅读
- android - 如何从 decodeImage(File('assets/logo.png').readAsBytesSync()) 加载图像;飘飘然
- python-3.x - PyMySQL 从变量中执行许多 INSERT 列表
- angular - 如何仅从 kendo-multiselect 下拉列表中删除第一个元素的关闭(x)按钮
- c# - 是否可以以编程方式滚动 WPF ListView 以便将所需的分组标题放置在其顶部?
- php - 从 MySQL 中随机生成的数据加载更多功能
- python - 如何通过 Django 通道 WebSocket 传递请求并调用 Django 视图
- bash - 早期问题的不同方面:从 geek_scripts 运行时,为什么不测试是否存在 Docker 工作不起作用?
- python - 格式化粗体文本
- java - 如何重复添加到 ArrayList
> 使用一个循环并且只有一个其他 ArrayList ? - html - 如何在 Angular 的组件文件中设置输入占位符文本