ASP.NET Core : how to log authorization exceptions

Viewed 149

Is there an elegant way of capturing the Authorization exception in ASP.NET without writing any middleware or AuthorizationRequirement class.

I am building the authorization policy in the following way.

services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .RequireClaim(JwtRegisteredClaimNames.Azp, authorizedParties)
            .RequireClaim(CustomClaimNames.Customer)
            .Build();
    });

I dont see any OnAuthorizationFailed event just like OnAuthenticationFailed :-)

It is possible to capture Authentication exception in the following way.

  bearerOptions.Events = new JwtBearerEvents()
  {
      OnAuthenticationFailed = context =>
      {
        Log.Logger.Error(context.Exception.ToString());
        return Task.CompletedTask;
      }
   };

But I did not find the similar way to capture Authorization exception.

There is OnForbidden event, but the Exception property is not available in the ForbiddenContext object.

0 Answers
Related