基于自定义策略的授权

基于自定义策略的授权

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

引用示例:Custom Policy-Based Authorization

最佳答案

您应该将IHttpContextAccessor实例注入(inject)到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();

关于c# - 如何使用AuthorizationHandlerContext访问ASP.NET Core 2基于自定义策略的授权中的当前HttpContext,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47809437/

10-10 05:05