Skip to content

Commit

Permalink
Added authorization exceptions and friends
Browse files Browse the repository at this point in the history
  • Loading branch information
david-driscoll committed Mar 17, 2022
1 parent c59718e commit aec6221
Show file tree
Hide file tree
Showing 27 changed files with 535 additions and 311 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ public async Task<Unit> Handle(Request request, CancellationToken cancellationTo
throw new NotFoundException();
}

// contrived for testing
if (rocket.Id == new LaunchRecordId(new Guid("bad361de-a6d5-425a-9cf6-f9b2dd236be6")))
{
throw new NotAuthorizedException("Unable to operate on given record");
}

_dbContext.Remove(rocket);
await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

Expand Down
1 change: 1 addition & 0 deletions src/AspNetCore/Conventions/AspNetCoreConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ public void Register(IConventionContext context, IConfiguration configuration, I
options =>
{
options.Filters.Add<NotFoundExceptionFilter>();
options.Filters.Add<NotAuthorizedExceptionFilter>();
options.Filters.Add<RequestFailedExceptionFilter>();
options.Filters.Add<SerilogLoggingActionFilter>(0);
options.Filters.Add<SerilogLoggingPageFilter>(0);
Expand Down
39 changes: 4 additions & 35 deletions src/AspNetCore/Conventions/FluentValidationConvention.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Reflection;
using System.Net;
using System.Reflection;
using FluentValidation;
using FluentValidation.AspNetCore;
using FluentValidation.Results;
Expand All @@ -16,7 +17,9 @@
using Rocket.Surgery.Conventions.DependencyInjection;
using Rocket.Surgery.Extensions;
using Rocket.Surgery.LaunchPad.AspNetCore.Validation;
using Rocket.Surgery.LaunchPad.Foundation;
using Rocket.Surgery.LaunchPad.Foundation.Validation;
using ProblemDetailsException = Rocket.Surgery.LaunchPad.Foundation.ProblemDetailsException;

namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions;

Expand Down Expand Up @@ -125,39 +128,5 @@ public void Register(IConventionContext context, IConfiguration configuration, I
.Configure<JsonOptions>(options => options.JsonSerializerOptions.Converters.Add(new ValidationProblemDetailsConverter()));

AddFluentValidationRules(services);

services.AddOptions<ProblemDetailsOptions>()
.Configure<IOptions<ApiBehaviorOptions>>(
(builder, apiBehaviorOptions) =>
{
builder.OnBeforeWriteDetails = (_, problemDetails) =>
{
if (
!problemDetails.Status.HasValue
|| !apiBehaviorOptions.Value.ClientErrorMapping.TryGetValue(problemDetails.Status.Value, out var clientErrorData)
) return;

problemDetails.Title ??= clientErrorData.Title ?? string.Empty;
problemDetails.Type ??= clientErrorData.Link;
};
builder.Map<ValidationException>(
exception => new FluentValidationProblemDetails(exception.Errors)
{
Status = StatusCodes.Status422UnprocessableEntity
}
);
builder.Map<Exception>(
(context, _) => context.Items[typeof(ValidationResult)] is ValidationResult,
(context, _) =>
{
var result = context.Items[typeof(ValidationResult)] as ValidationResult;
return new FluentValidationProblemDetails(result!.Errors)
{
Status = StatusCodes.Status422UnprocessableEntity
};
}
);
}
);
}
}
52 changes: 51 additions & 1 deletion src/AspNetCore/Conventions/ProblemDetailsConvention.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
using Hellang.Middleware.ProblemDetails;
using FluentValidation;
using FluentValidation.Results;
using Hellang.Middleware.ProblemDetails;
using Hellang.Middleware.ProblemDetails.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Rocket.Surgery.Conventions;
using Rocket.Surgery.Conventions.DependencyInjection;
using Rocket.Surgery.LaunchPad.AspNetCore.Validation;
using Rocket.Surgery.LaunchPad.Foundation;

namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions;

Expand All @@ -24,5 +31,48 @@ public void Register(IConventionContext context, IConfiguration configuration, I
services
.AddProblemDetails()
.AddProblemDetailsConventions();

services.AddOptions<ProblemDetailsOptions>()
.Configure<IOptions<ApiBehaviorOptions>>(
(builder, apiBehaviorOptions) =>
{
var currentIncludeExceptionDetails = builder.IncludeExceptionDetails;
builder.IncludeExceptionDetails = (httpContext, exception) =>
exception is not IProblemDetailsData && currentIncludeExceptionDetails(httpContext, exception);
builder.OnBeforeWriteDetails = (_, problemDetails) =>
{
if (
!problemDetails.Status.HasValue
|| !apiBehaviorOptions.Value.ClientErrorMapping.TryGetValue(problemDetails.Status.Value, out var clientErrorData)
)
{
return;
}

problemDetails.Title ??= clientErrorData.Title;
problemDetails.Type ??= clientErrorData.Link;
};
// builder.MapToProblemDetailsDataException<NotFoundException>(StatusCodes.Status404NotFound);
// builder.MapToProblemDetailsDataException<RequestFailedException>(StatusCodes.Status400BadRequest);
// builder.MapToProblemDetailsDataException<NotAuthorizedException>(StatusCodes.Status403Forbidden);
builder.Map<ValidationException>(
exception => new FluentValidationProblemDetails(exception.Errors)
{
Status = StatusCodes.Status422UnprocessableEntity
}
);
builder.Map<Exception>(
(context, ex) => ex is not IProblemDetailsData && context.Items[typeof(ValidationResult)] is ValidationResult,
(context, _) =>
{
var result = context.Items[typeof(ValidationResult)] as ValidationResult;
return new FluentValidationProblemDetails(result!.Errors)
{
Status = StatusCodes.Status422UnprocessableEntity
};
}
);
}
);
}
}
42 changes: 42 additions & 0 deletions src/AspNetCore/Conventions/ProblemDetailsOptionsExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Hellang.Middleware.ProblemDetails;
using Microsoft.AspNetCore.Mvc;
using Rocket.Surgery.LaunchPad.Foundation;

namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions;

/// <summary>
/// Extensions to ProblemDetailsOptions
/// </summary>
public static class ProblemDetailsOptionsExtensions
{
/// <summary>
/// Creates a mapping for an exception that implements <see cref="IProblemDetailsData" /> with the given status code
/// </summary>
/// <param name="options"></param>
/// <param name="statusCode"></param>
/// <typeparam name="TException"></typeparam>
public static void MapToProblemDetailsDataException<TException>(this ProblemDetailsOptions options, int statusCode)
where TException : Exception, IProblemDetailsData
{
options.Map<TException>((_, ex) => ConstructProblemDetails(ex, statusCode));
}

private static ProblemDetails ConstructProblemDetails<TException>(TException ex, int statusCode) where TException : Exception, IProblemDetailsData
{
var details = new ProblemDetails
{
Detail = ex.Message,
Title = ex.Title,
Type = ex.Link,
Instance = ex.Instance,
Status = statusCode
};
foreach (var item in ex.Properties)
{
if (details.Extensions.ContainsKey(item.Key)) continue;
details.Extensions.Add(item);
}

return details;
}
}
18 changes: 18 additions & 0 deletions src/AspNetCore/Filters/NotAuthorizedExceptionFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Rocket.Surgery.LaunchPad.Foundation;

namespace Rocket.Surgery.LaunchPad.AspNetCore.Filters;

/// <summary>
/// Not authorized exception that catches not authorized messages that might have been thrown by calling code.
/// </summary>
internal class NotAuthorizedExceptionFilter : ProblemDetailsExceptionFilter<NotAuthorizedException>
{
/// <summary>
/// Not authorized exception that catches not authorized messages that might have been thrown by calling code.
/// </summary>
public NotAuthorizedExceptionFilter(ProblemDetailsFactory problemDetailsFactory) : base(StatusCodes.Status403Forbidden, problemDetailsFactory)
{
}
}
42 changes: 2 additions & 40 deletions src/AspNetCore/Filters/NotFoundExceptionFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,51 +11,13 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Filters;
/// <summary>
/// Not found exception that catches not found messages that might have been thrown by calling code.
/// </summary>
internal class NotFoundExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
internal class NotFoundExceptionFilter : ProblemDetailsExceptionFilter<NotFoundException>
{
private readonly ProblemDetailsFactory _problemDetailsFactory;

/// <summary>
/// Create a new NotFoundExceptionFilter
/// </summary>
/// <param name="problemDetailsFactory"></param>
public NotFoundExceptionFilter(ProblemDetailsFactory problemDetailsFactory)
public NotFoundExceptionFilter(ProblemDetailsFactory problemDetailsFactory) : base(StatusCodes.Status404NotFound, problemDetailsFactory)
{
_problemDetailsFactory = problemDetailsFactory;
}

/// <inheritdoc />
public Task OnExceptionAsync(ExceptionContext context)
{
OnException(context);
return Task.CompletedTask;
}

/// <inheritdoc />
public void OnException(ExceptionContext context)
{
if (context.Exception is NotFoundException exception)
{
context.ExceptionHandled = true;
var problemDetails = _problemDetailsFactory.CreateProblemDetails(
context.HttpContext,
StatusCodes.Status404NotFound,
detail: exception.Message,
title: exception.Title,
type: exception.Link,
instance: exception.Instance
);

foreach (var item in exception.Properties)
{
if (problemDetails.Extensions.ContainsKey(item.Key)) continue;
problemDetails.Extensions.Add(item);
}

context.Result = new ObjectResult(problemDetails)
{
StatusCode = StatusCodes.Status404NotFound
};
}
}
}
72 changes: 72 additions & 0 deletions src/AspNetCore/Filters/ProblemDetailsExceptionFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Rocket.Surgery.LaunchPad.Foundation;

namespace Rocket.Surgery.LaunchPad.AspNetCore.Filters;

/// <summary>
/// An exception filter that catches the given problem details exception and uses the given status code to return the result
/// </summary>
/// <typeparam name="T"></typeparam>
[PublicAPI]
public abstract class ProblemDetailsExceptionFilter<T> : IExceptionFilter, IAsyncExceptionFilter
where T : Exception, IProblemDetailsData
{
private readonly int _statusCode;
private readonly ProblemDetailsFactory _problemDetailsFactory;

/// <summary>
/// Create the problem details filter
/// </summary>
/// <param name="statusCode"></param>
/// <param name="problemDetailsFactory"></param>
protected ProblemDetailsExceptionFilter(int statusCode, ProblemDetailsFactory problemDetailsFactory)
{
_statusCode = statusCode;
_problemDetailsFactory = problemDetailsFactory;
}

/// <summary>
/// Allows changing the problem details before it is returned
/// </summary>
/// <param name="problemDetails"></param>
/// <returns></returns>
protected virtual ProblemDetails CustomizeProblemDetails(ProblemDetails problemDetails)
{
return problemDetails;
}

/// <inheritdoc />
public Task OnExceptionAsync(ExceptionContext context)
{
OnException(context);
return Task.CompletedTask;
}

/// <inheritdoc />
public void OnException(ExceptionContext context)
{
if (context.Exception is T exception)
{
context.ExceptionHandled = true;
var problemDetails = _problemDetailsFactory.CreateProblemDetails(
context.HttpContext,
_statusCode,
detail: exception.Message,
title: exception.Title,
type: exception.Link,
instance: exception.Instance
);

foreach (var item in exception.Properties)
{
if (problemDetails.Extensions.ContainsKey(item.Key)) continue;
problemDetails.Extensions.Add(item);
}

problemDetails = CustomizeProblemDetails(problemDetails);
context.Result = new ObjectResult(problemDetails) { StatusCode = _statusCode };
}
}
}
47 changes: 4 additions & 43 deletions src/AspNetCore/Filters/RequestFailedExceptionFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,53 +9,14 @@
namespace Rocket.Surgery.LaunchPad.AspNetCore.Filters;

/// <summary>
/// Not found exception that catches not found messages that might have been thrown by calling code.
/// Request failed exception that catches issues that might have been thrown by calling code.
/// </summary>
internal class RequestFailedExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
internal class RequestFailedExceptionFilter : ProblemDetailsExceptionFilter<RequestFailedException>
{
private readonly ProblemDetailsFactory _problemDetailsFactory;

/// <summary>
/// Not found exception that catches not found messages that might have been thrown by calling code.
/// Request failed exception that catches issues that might have been thrown by calling code.
/// </summary>
public RequestFailedExceptionFilter(ProblemDetailsFactory problemDetailsFactory)
public RequestFailedExceptionFilter(ProblemDetailsFactory problemDetailsFactory) : base(StatusCodes.Status400BadRequest, problemDetailsFactory)
{
_problemDetailsFactory = problemDetailsFactory;
}

/// <inheritdoc />
public Task OnExceptionAsync(ExceptionContext context)
{
OnException(context);
return Task.CompletedTask;
}

/// <inheritdoc />
public void OnException(ExceptionContext context)
{
if (context.Exception is RequestFailedException exception)
{
context.ExceptionHandled = true;
var problemDetails = _problemDetailsFactory.CreateProblemDetails(
context.HttpContext,
StatusCodes.Status400BadRequest,
detail: exception.Message,
title: exception.Title,
type: exception.Link,
instance: exception.Instance
);

foreach (var item in exception.Properties)
{
if (problemDetails.Extensions.ContainsKey(item.Key))
continue;
problemDetails.Extensions.Add(item);
}

context.Result = new ObjectResult(problemDetails)
{
StatusCode = StatusCodes.Status400BadRequest
};
}
}
}
Loading

0 comments on commit aec6221

Please sign in to comment.