如何使用AuthorizationHandlerContext访问ASP.NET Core 2基于自定义策略的授权中的当前HttpContext

时间:2017-12-14 09:01:00

标签: c# asp.net-core .net-core asp.net-core-2.0

如何访问当前的HttpContext以检查ASP.NET Core 2中基于自定义策略的授权的AuthorizationHandlerContext内的路由和参数?

参考示例:Custom Policy-Based Authorization

4 个答案:

答案 0 :(得分:19)

您应该将IHttpContextAccessor的实例注入AuthorizationHandler

example的上下文中,可能如下所示:

public class BadgeEntryHandler : AuthorizationHandler<EnterBuildingRequirement>
{
    IHttpContextAccessor _httpContextAccessor = null;

    public BadgeEntryHandler(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override Task HandleRequirementAsync(
        AuthorizationContext context, 
        EnterBuildingRequirement requirement)
    {
        HttpContext httpContext = _httpContextAccessor.HttpContext; // Access context here

        if (context.User.HasClaim(c => c.Type == ClaimTypes.BadgeId &&
                                       c.Issuer == "http://microsoftsecurity"))
        {
            context.Succeed(requirement);
            return Task.FromResult(0);
        }
    }
}

您可能需要在DI设置中注册(如果您的某个依赖项还没有),如下所示:

services.AddHttpContextAccessor();

答案 1 :(得分:3)

您可以将IHttpContextAccessor注入AuthorizationHandler的构造函数。

e.g。

public class MyAuthorizationHandler : AuthorizationHandler<MyRequirement>
{
    private IHttpContextAccessor _contextAccessor;

    public MyAuthorizationHandler (IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
        MinimumPermissionLevelRequirement requirement) {

        var httpContext = _contextAccessor.HttpContext;
        // do things
    }
}

答案 2 :(得分:1)

无需注射,简单的解决方案!

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
        {
                var authFilterCtx = (Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)context.Resource;
                var httpContext = authFilterCtx.HttpContext;  
        }

答案 3 :(得分:0)

如果是 MVC 上下文,您可以从 HttpContext 访问 RouteDataAuthorizationContext context 以及 MVC 提供的所有其他内容:

var mvcContext = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;

if (mvcContext != null)
{
    // Examine MVC specific things like routing data.
}

https://jakeydocs.readthedocs.io/en/latest/security/authorization/policies.html#accessing-mvc-request-context-in-handlers