我正在将Web API从.net Framework迁移到.net Core。如果该应用程序在私有服务器上运行,则旧版本可以忽略控制器上的Authorize Attribute。这是代码。我知道.net core 3.1不提供自定义AuthorizeAttributes。那不是我的问题。
// A custom AuthroizeAttribute
public class ConditionalAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext httpContext)
{
if (environment_private())
return true;
else
return base.IsAuthorized(httpContext);
}
private bool environment_private()
{
// code that will tell you if you are in your dev environment or not
return Properties.Settings.Default.PrivateServer;
}
}
// How it was called from the controller
[ConditionalAuthorize(Roles = "MyRole")]
[Route(...)]
// More code for controller
在私有服务器上运行项目时,我只需要一种简单的方法来授权所有请求(由appSettings.json中的变量确定)。我已经尝试过政策,但是面临以下困难:
1)我无法将配置中的变量从控制器传递给参数化的授权属性。
2)我无法将配置注入到参数化的授权属性中。
这实际上消除了我以任何方式遵循本指南的能力:https : //docs.microsoft.com/zh-cn/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-2.2
这导致了我的问题:如何使用appSettings.json中的值覆盖请求是否检查角色?
经过大量研究,我找到了使用的方法TypeFilterAttribute
。本质上,这是相同的方法(使用自定义属性过滤所有请求并检查自定义属性中的条件),只是我使用了.net Core支持的方法。
如果您尝试解决相同的问题,这是我的解决方案的确切步骤。
public class YourAttributeNameAttribute : TypeFilterAttribute
{
public YourAttributeNameAttribute(string role) : base(typeof(YourFilterNameFilter))
{
Arguments = new object[] { role };
}
}
public class YourFilterNameFilter : IAuthorizationFilter
{
private readonly string Role;
public YourFilterNameFilter(string role)
{
Role = role;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();
// If private server, ignore roles
if (private_server_logic_here)
return;
var user = context.HttpContext.User;
// Check role if on public server
if (!user.IsInRole(Role))
{
context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Unauthorized);
return;
}
}
}
[YourAttributeName("role_name")]
[Route("api/my_route")]
[HttpGet]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句