-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthExceptionMiddleware.cs
104 lines (88 loc) · 3.38 KB
/
AuthExceptionMiddleware.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using FluentValidation;
using aiof.auth.data;
namespace aiof.auth.core
{
public class AuthExceptionMiddleware
{
private readonly ILogger _logger;
private readonly IWebHostEnvironment _env;
private readonly RequestDelegate _next;
private const string _defaultMessage = "An unexpected error has occurred";
private const string _defaultValidationMessage = "One or more validation errors have occurred. Please see errors for details";
public AuthExceptionMiddleware(
ILogger<AuthExceptionMiddleware> logger,
IWebHostEnvironment env,
RequestDelegate next)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_env = env ?? throw new ArgumentNullException(nameof(env));
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception e)
{
if (httpContext.Response.HasStarted)
{
_logger.LogWarning("The response has already started, the http status code middleware will not be executed.");
throw;
}
var id = string.IsNullOrEmpty(httpContext?.TraceIdentifier)
? Guid.NewGuid().ToString()
: httpContext.TraceIdentifier;
_logger.LogError(
e,
$"an exception was thrown during the request. {id}");
await WriteExceptionResponseAsync(
httpContext,
e,
id);
}
}
private async Task WriteExceptionResponseAsync(
HttpContext httpContext,
Exception e,
string id)
{
var canViewSensitiveInfo = _env
.IsDevelopment();
var problem = new AuthProblemDetail()
{
Message = canViewSensitiveInfo
? e.Message
: _defaultMessage,
Code = StatusCodes.Status500InternalServerError,
TraceId = $"aiof:auth:error:{id}"
};
if (e is AuthException ae)
{
problem.Code = ae.StatusCode;
problem.Message = ae.Message;
}
else if (e is ValidationException ve)
{
problem.Code = StatusCodes.Status400BadRequest;
problem.Message = _defaultValidationMessage;
problem.Errors = ve.Errors.Select(x => x.ErrorMessage);
}
var problemjson = JsonSerializer
.Serialize(problem, new JsonSerializerOptions { IgnoreNullValues = true });
httpContext.Response.StatusCode = problem.Code ?? StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "application/problem+json";
await httpContext.Response
.WriteAsync(problemjson);
}
}
}