如何查看哪个AuthorizeAttribute失败的ASP.NET Core

时间:2019-02-19 11:30:24

标签: asp.net-core .net-core asp.net-authorization

我正在尝试找出是否有一种简单的方法来获取ASP.NET Core记录哪个[Authorize]属性失败的信息。我混合使用“角色”和“策略”授权属性,但是只要有一个失败,日志就会显示:

enter image description here

很明显,这是正确的行为,它不会让具有错误权限的人进入,但是,如果您有多个属性,那么必须去找出哪个失败是很痛苦的。如果日志仅显示Authorization failed for Policy X,则很容易找出失败原因。

有人知道我目前是否可以通过我不知道的某些选项来实现这一目标?

编辑:例如:如果我有[Authorize(Policy = "Policy 1")][Authorize(Policy = "Policy 2")],而只有“策略2”失败。我希望看到一些东西告诉我“政策2”失败了。

3 个答案:

答案 0 :(得分:1)

对于RolesPolicy,它们被转换为需求RolesAuthorizationRequirement或您的自定义需求,例如MinimumAgeRequirement

对于Authorization failed.,这是由DefaultAuthorizationServiceAuthorizeAsync中记录的,您可能无法获得确切的名称,例如Policy 1Policy 2。您可以获得Policy的要求。

尝试检查以下解决方法是否满足您的要求。

  1. 实施自定义DefaultAuthorizationService

    public class CustomAuthorizationService : DefaultAuthorizationService, IAuthorizationService
    {
        private readonly AuthorizationOptions _options;
        private readonly IAuthorizationHandlerContextFactory _contextFactory;
        private readonly IAuthorizationHandlerProvider _handlers;
        private readonly IAuthorizationEvaluator _evaluator;
        private readonly IAuthorizationPolicyProvider _policyProvider;
        private readonly ILogger _logger;
    
        public CustomAuthorizationService(IAuthorizationPolicyProvider policyProvider
            , IAuthorizationHandlerProvider handlers
            , ILogger<DefaultAuthorizationService> logger
            , IAuthorizationHandlerContextFactory contextFactory
            , IAuthorizationEvaluator evaluator
            , IOptions<AuthorizationOptions> options) 
            : base(policyProvider, handlers, logger, contextFactory, evaluator, options)
        {
            _options = options.Value;
            _handlers = handlers;
            _policyProvider = policyProvider;
            _logger = logger;
            _evaluator = evaluator;
            _contextFactory = contextFactory;
        }
    
        public new async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements)
        {
            if (requirements == null)
            {
                throw new ArgumentNullException(nameof(requirements));
            }
    
            var authContext = _contextFactory.CreateContext(requirements, user, resource);
            var handlers = await _handlers.GetHandlersAsync(authContext);
            foreach (var handler in handlers)
            {
                await handler.HandleAsync(authContext);
                if (!_options.InvokeHandlersAfterFailure && authContext.HasFailed)
                {
                    break;
                }
            }
    
            var result = _evaluator.Evaluate(authContext);
            if (result.Succeeded)
            {
                _logger.LogInformation($"Authorization is successed for { result.Failure.FailedRequirements }" );
                //_logger.UserAuthorizationSucceeded();
            }
            else
            {
                //var r = result.Failure.FailedRequirements.Select(requirement => new { Requirement = requirement.GetType() });
                var json = JsonConvert.SerializeObject(result.Failure.FailedRequirements);
                _logger.LogInformation($"Authorization is failed for { json }");
                //_logger.UserAuthorizationFailed();
            }
            return result;
        }
    
    }
    
  2. 替换内置的DefaultAuthorizationService

    services.AddAuthorization(config =>
    {
        config.AddPolicy("T1", policy => policy.AddRequirements(new MinimumAgeRequirement(21)));
    });
    
    services.Replace(ServiceDescriptor.Transient<IAuthorizationService, CustomAuthorizationService>());
    

答案 1 :(得分:0)

您可以在Middlewares

中处理并记录此内容
public class AuthHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ErrorHandlingMiddleware> _logger;

    public AuthHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, IHostingEnvironment env /* other scoped dependencies */)
    {  

        await _next(context);

        if (context.Response.StatusCode == 401)
           _logger.LogInformation($"'{context.User.Identity.Name}' is unauthorized");
    }
}

在您的starup配置中,

public void Configure(IApplicationBuilder app, ... )
{
      ....
      app.UseMiddleware<AuthHandlerMiddleware>();
}

答案 2 :(得分:0)

Microsoft默认在.NET 5.0中实现此功能,有关详细信息和PR的链接,请参见相关的GitHub问题。

https://github.com/aspnet/AspNetCore/issues/7789