Home > Enterprise >  How to return custom Exception
How to return custom Exception

Time:01-26

I added the [Authorization] attribute to the below action to protect it from unauthorized access. I'm wondering if it's possible to return a custom error/exception for this?

In postman, it only shows the 401 status but the response of the body is empty.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [Authorize]
    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

CodePudding user response:

If you are using.NET 5 and above you can implement the IAuthorizationMiddlewareResultHandler and return whatever http response code and data you want on the failed authorization. You can even return different response codes and data based on different authorization policy failures that you can define yourself

public class CustomAuthorizationMiddlewareResultHandler : 
 IAuthorizationMiddlewareResultHandler
{
   private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();

    public async Task HandleAsync(
    RequestDelegate next,
    HttpContext context,
    AuthorizationPolicy policy,
    PolicyAuthorizationResult authorizeResult)
   {
       if (policyAuthorizationResult.Forbidden &&
           policyAuthorizationResult.AuthorizationFailure.FailedRequirements.OfType<Show404Requirement>().Any();) 
          { 
               var bytes = Encoding.UTF8.GetBytes("Not found bro");

               await HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
               context.Response.StatusCode = StatusCodes.Status404NotFound;
               return;
          }

          await DefaultHandler.HandleAsync(requestDelegate, httpContext, authorizationPolicy, 
                           policyAuthorizationResult);
   }
}

More details on the topic here https://learn.microsoft.com/en-us/aspnet/core/security/authorization/customizingauthorizationmiddlewareresponse?view=aspnetcore-5.0

  • Related