Cal*_*son 5 c# authorize .net-core
我正在将 Web API 从 .net Framework 迁移到 .net Core。如果应用程序在专用服务器上运行,旧版本能够忽略控制器上的授权属性。这是代码。我知道 .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
Run Code Online (Sandbox Code Playgroud)
我只需要一种简单的方法来授权在我们的私人服务器上运行项目时的所有请求(由 appSettings.json 中的变量确定)。我尝试过政策,但面临以下困难:
1)我无法将配置中的变量从控制器传递到参数化授权属性。
2)我无法将配置注入参数化授权属性。
这实际上消除了我以任何方式遵循本指南的能力:https://learn.microsoft.com/en-us/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 };
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
[YourAttributeName("role_name")]
[Route("api/my_route")]
[HttpGet]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1592 次 |
| 最近记录: |