如何使用AuthorizationHandlerContext访问ASP.NET Core 2基于自定义策略的授权中的当前HttpContext [英] How to access current HttpContext in ASP.NET Core 2 Custom Policy-Based Authorization with AuthorizationHandlerContext

查看:487
本文介绍了如何使用AuthorizationHandlerContext访问ASP.NET Core 2基于自定义策略的授权中的当前HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I access current HttpContext to check for route and parameters inside AuthorizationHandlerContext of Custom Policy-Based Authorization inside ASP.NET Core 2?

参考示例:基于自定义策略的授权

推荐答案

您应该注入 IHttpContextAccessor 放入您的 AuthorizationHandler

在您的示例的上下文中,这看起来像以下内容:

In the context of your example, this may look like the following:

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设置中(如果还没有依赖项的话),如下所示:

You may need to register this in your DI setup (if one of your dependencies has not already), as follows:

services.AddHttpContextAccessor();

这篇关于如何使用AuthorizationHandlerContext访问ASP.NET Core 2基于自定义策略的授权中的当前HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆