[英]How to get Controller and Action inside AuthorizationHandler?
I am just wondering is it possible to get Controller
and Action
in an AuthorizationHandler
?.我只是想知道是否有可能在
AuthorizationHandler
中获得Controller
和Action
? It is needed in order to be able to validate user's role based on the requested action.需要它才能根据请求的操作验证用户的角色。
I'm able to get reference to HttpContext
.我可以参考
HttpContext
。 But the HttpContext.Request.RouteValues
seems inaccessible.但是
HttpContext.Request.RouteValues
似乎无法访问。
Does anyone has any idea?有人知道吗? my code:
我的代码:
public class RoleHandler :
AuthorizationHandler<RoleRequirement>
{
private readonly IUnitOfWork _context;
private readonly IHttpContextAccessor _httpContext;
public RoleHandler(IHttpContextAccessor httpContext, IUnitOfWork context)
{
_context = context;
_httpContext = httpContext;
}
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext authorizationcontext,
RoleRequirement requirement)
{
var roleClaim = authorizationcontext.User.Claims
.Where(c =>
c.Type == ClaimTypes.Role);
var routeData = authorizationcontext.Resource ;
if (ThisRoleIsAllowed(roleClaim, requirement.ActionName).Result)
authorizationcontext.Succeed(requirement);
return Task.CompletedTask;
}
Let me summarize here what we had discussed so far.让我在这里总结一下我们到目前为止所讨论的内容。 (My intention is to capture the valuable information from the comments).
(我的目的是从评论中获取有价值的信息)。
The OP wants to implement a resource ( endpoint ) based Authorization . OP 希望实现基于资源(端点)的授权。 (The ASP.NET Core standard is the role based.) In order to do so, the following information is needed:
(ASP.NET 核心标准是基于角色的。)为此,需要以下信息:
Based on these and the role claim the Authorization logic easily can decide whether or not the requester is allowed to access the resource.基于这些和角色声明,授权逻辑可以轻松地决定是否允许请求者访问资源。
To able to retrieve the controller's name and action's name I suggested the following:为了能够检索控制器的名称和操作的名称,我建议如下:
GetEndPoint
extension method on the HttpContext
HttpContext
上调用GetEndPoint
扩展方法GetMetadata<ControllerActionDescriptor>
on the Endpoint
Endpoint
上调用GetMetadata<ControllerActionDescriptor>
ControllerName
and ActionName
on the ControllerActionDescriptor
( 1 )ControllerActionDescriptor
上的ControllerName
和ActionName
( 1 ) So, to sum up:所以,总结一下:
public class RoleHandler: AuthorizationHandler<RoleRequirement>
{
private readonly IHttpContextAccessor _httpContextAccessor;
protected override Task HandleRequirementAsync
(AuthorizationHandlerContext authorizationcontext, RoleRequirement requirement)
{
var endpoint = _httpContextAccessor.HttpContext.GetEndpoint();
var descriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
var controllerName = descriptor.ControllerName;
//...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.