gpt4 book ai didi

asp.net-core - .Net Core 3 自定义授权策略 - 访问 Action 动词

转载 作者:行者123 更新时间:2023-12-03 16:03:37 26 4
gpt4 key购买 nike

我正在尝试将一些旧代码移植到 .Net Core 3。

使用旧的 AuthorizeAttibutes,您可以从 HttpActionContext 获得 Action 的动词
通过
var verb = actionContext.Request.Method.Method;
在 Core 3.0 中,HttpActionContext 现在已更改为 AuthorizationHandlerContext。

我看过一些帖子提到使用:
var filterContext = context.Resource as AuthorizationFilterContext;var httpMethod = filterContext.HttpContext.Request.Method;
但在 .Net Core 3 中,我没有在 context.Resource 上看到普通 Controller 或 api Controller 的 AuthorizationFilterContext 。

关于如何获得 Action 请求中使用的动词的任何想法/指示?

编辑 :所以在@xing-zou 的帮助下,我能够执行以下 POC 以获取唯一的路由键,我可以将它与我在数据库中的路由和分配给它们的角色进行比较。

如果用户属于与路由关联的角色,则用户将获得访问权限,否则 403 Forbidden

    public class AccessToRouteHandler : AuthorizationHandler<AccessToRouteRequirement>
{
private readonly IHttpContextAccessor httpContextAccessor;

private readonly DbContext dbContext;

public AccessToRouteHandler(IHttpContextAccessor httpContextAccessor, DbContext dbContext)
{
this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
this.dbContext = dbContext;
}

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessToRouteRequirement requirement)
{
var filterContext = context.Resource as AuthorizationFilterContext;
var routeInfo = context.Resource as RouteEndpoint;
var response = filterContext?.HttpContext.Response;

if (!context.User.Identity.IsAuthenticated || string.IsNullOrEmpty(context.User.Identity.Name))
{
response?.OnStarting(async () =>
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
});

context.Fail();
return Task.CompletedTask;
}

var verb = this.httpContextAccessor.HttpContext.Request.Method;
var routeKey = string.Empty;

if (context.Resource is Endpoint endpoint)
{
var cad = endpoint.Metadata.OfType<ControllerActionDescriptor>().FirstOrDefault();

var controllerFullName = cad.ControllerTypeInfo.FullName;
var actionName = cad.ActionName;
var bindings = cad.Parameters;
var actionParams = ".";

if (bindings.Any())
{
bindings.ToList().ForEach(p => actionParams += p.ParameterType.Name + ".");
}

routeKey = $"{controllerFullName}.{actionName}{actionParams}{verb}";
}

var route = dbContext.Routes
.Include(t => t.Roles)
.FirstOrDefault(r => r.RouteKey == routeKey);

if (route != null && route.Roles.Any(role => context.User.HasClaim(c => c.Value == role)))
{
// user belong to a role associated to the route.
context.Succeed(requirement);
return Task.CompletedTask;
}

response?.OnStarting(async () =>
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
});

context.Fail();
return Task.CompletedTask;
}
}

最佳答案

在启用端点路由的 asp.net core 3.0 中,您可以注册 IHttpContextAccessor要获取当前的 HttpContext,则可以获取 http方法。

下面以基于策略的授权为例:

public class AccountRequirement : IAuthorizationRequirement { }

public class AccountHandler : AuthorizationHandler<AccountRequirement>
{
private readonly IHttpContextAccessor _httpContextAccessor;

public AccountHandler(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
AccountRequirement requirement)
{

var httpMethod = _httpContextAccessor.HttpContext.Request.Method;

if (httpMethod == "POST")
{
context.Succeed(requirement);
}


return Task.CompletedTask;
}
}

在启动中:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
options.AddPolicy("Account",
policy => policy.Requirements.Add(new AccountRequirement()));
});

services.AddSingleton<IAuthorizationHandler, AccountHandler>();
}

关于asp.net-core - .Net Core 3 自定义授权策略 - 访问 Action 动词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57973981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com