| | | 1 | | using ArturRios.Configuration.Providers; |
| | | 2 | | using ArturRios.Output; |
| | | 3 | | using ArturRios.Util.WebApi.Configuration; |
| | | 4 | | using ArturRios.Util.WebApi.Middleware; |
| | | 5 | | using ArturRios.Util.WebApi.Security.Attributes; |
| | | 6 | | using ArturRios.Util.WebApi.Security.Authentication; |
| | | 7 | | using ArturRios.Util.WebApi.Security.Configuration; |
| | | 8 | | using ArturRios.Util.WebApi.Security.Interfaces; |
| | | 9 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 10 | | using Microsoft.AspNetCore.Http; |
| | | 11 | | using Newtonsoft.Json; |
| | | 12 | | |
| | | 13 | | namespace ArturRios.Util.WebApi.Security.Middleware; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Authenticates requests by extracting one token (from the header, a cookie, or either, per |
| | | 17 | | /// <see cref="AuthenticationOptions.Source"/>) and running it through the enabled |
| | | 18 | | /// <see cref="ITokenValidator"/>s in order; the first that resolves a user attaches it to |
| | | 19 | | /// <c>HttpContext.Items["User"]</c>. Swagger and <see cref="AllowAnonymousAttribute"/> endpoints are skipped. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="next">The next middleware in the pipeline.</param> |
| | | 22 | | /// <param name="settings">Configuration used to detect Swagger routes.</param> |
| | | 23 | | /// <param name="options">Controls the token source and which validators run.</param> |
| | | 24 | | /// <param name="validators">The enabled validators, tried in registration order (app JWT first, Google second).</param> |
| | 6 | 25 | | public class AuthenticationMiddleware( |
| | 6 | 26 | | RequestDelegate next, |
| | 6 | 27 | | SettingsProvider settings, |
| | 6 | 28 | | AuthenticationOptions options, |
| | 6 | 29 | | IEnumerable<ITokenValidator> validators) : WebApiMiddleware |
| | | 30 | | { |
| | 6 | 31 | | private readonly ITokenValidator[] _validators = validators.ToArray(); |
| | | 32 | | |
| | | 33 | | /// <summary>Validates the request token and, on success, attaches the authenticated user before invoking the next m |
| | | 34 | | /// <param name="context">The current HTTP context.</param> |
| | | 35 | | public async Task InvokeAsync(HttpContext context) |
| | 6 | 36 | | { |
| | 6 | 37 | | var endpoint = context.GetEndpoint(); |
| | | 38 | | |
| | 6 | 39 | | var skipRoute = |
| | 6 | 40 | | IsSwaggerRoute(context.Request.Path.Value ?? string.Empty) || |
| | 6 | 41 | | endpoint?.Metadata.GetMetadata<AllowAnonymousAttribute>() is not null; |
| | | 42 | | |
| | 6 | 43 | | if (skipRoute) |
| | 1 | 44 | | { |
| | 1 | 45 | | await next(context); |
| | | 46 | | |
| | 1 | 47 | | return; |
| | | 48 | | } |
| | | 49 | | |
| | 5 | 50 | | var token = TokenExtractor.Extract(context, options.Source, options.CookieName); |
| | | 51 | | |
| | 5 | 52 | | string? lastError = null; |
| | | 53 | | |
| | 23 | 54 | | foreach (var validator in _validators) |
| | 6 | 55 | | { |
| | 6 | 56 | | var (user, error) = await validator.ValidateAsync(token, context); |
| | | 57 | | |
| | 6 | 58 | | if (user is not null) |
| | 4 | 59 | | { |
| | 4 | 60 | | context.Items["User"] = user; |
| | | 61 | | |
| | 4 | 62 | | await next(context); |
| | | 63 | | |
| | 4 | 64 | | return; |
| | | 65 | | } |
| | | 66 | | |
| | 2 | 67 | | lastError = error; |
| | 2 | 68 | | } |
| | | 69 | | |
| | 1 | 70 | | await WriteUnauthorized(context, lastError); |
| | 6 | 71 | | } |
| | | 72 | | |
| | | 73 | | private static async Task WriteUnauthorized(HttpContext context, string? authError) |
| | 1 | 74 | | { |
| | 1 | 75 | | var output = ProcessOutput.New.WithError(authError ?? "Unauthorized"); |
| | | 76 | | |
| | 1 | 77 | | if (context.Response.HasStarted) |
| | 0 | 78 | | { |
| | 0 | 79 | | return; |
| | | 80 | | } |
| | | 81 | | |
| | 1 | 82 | | context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
| | 1 | 83 | | context.Response.ContentType = "application/json"; |
| | | 84 | | |
| | 1 | 85 | | var payload = JsonConvert.SerializeObject(output); |
| | | 86 | | |
| | 1 | 87 | | await context.Response.WriteAsync(payload); |
| | 1 | 88 | | } |
| | | 89 | | |
| | | 90 | | private bool IsSwaggerRoute(string path) => |
| | 6 | 91 | | settings.GetBool(AppSettingsKeys.SwaggerEnabled) is true && |
| | 6 | 92 | | path.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase); |
| | | 93 | | } |