| | | 1 | | using ArturRios.Configuration.Providers; |
| | | 2 | | using ArturRios.Output; |
| | | 3 | | using ArturRios.Util.WebApi.Configuration; |
| | | 4 | | using ArturRios.Util.WebApi.Extensions; |
| | | 5 | | using ArturRios.Util.WebApi.Middleware; |
| | | 6 | | using ArturRios.Util.WebApi.Security.Attributes; |
| | | 7 | | using ArturRios.Util.WebApi.Security.Configuration; |
| | | 8 | | using ArturRios.Util.WebApi.Security.Extensions; |
| | | 9 | | using ArturRios.Util.WebApi.Security.Interfaces; |
| | | 10 | | using Microsoft.AspNetCore.Http; |
| | | 11 | | |
| | | 12 | | namespace ArturRios.Util.WebApi.Security.Middleware; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Authenticates requests by extracting one token (from the header, a cookie, or either, per |
| | | 16 | | /// <see cref="AuthenticationOptions.Source"/>) and running it through the enabled |
| | | 17 | | /// <see cref="ITokenValidator"/>s in order; the first that resolves a user attaches it to |
| | | 18 | | /// <c>HttpContext.Items["User"]</c>. Swagger and <see cref="AllowAnonymousAttribute"/> endpoints are skipped. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="next">The next middleware in the pipeline.</param> |
| | | 21 | | /// <param name="settings">Configuration used to detect Swagger routes.</param> |
| | | 22 | | /// <param name="options">Controls the token source and which validators run.</param> |
| | | 23 | | /// <param name="validators">The enabled validators, tried in registration order (app JWT first, Google second).</param> |
| | 20 | 24 | | public class AuthenticationMiddleware( |
| | 20 | 25 | | RequestDelegate next, |
| | 20 | 26 | | SettingsProvider settings, |
| | 20 | 27 | | AuthenticationOptions options, |
| | 20 | 28 | | IEnumerable<ITokenValidator> validators) : WebApiMiddleware |
| | | 29 | | { |
| | | 30 | | private const string MissingTokenError = "Authentication token not provided"; |
| | | 31 | | private const string UnauthorizedError = "Unauthorized"; |
| | | 32 | | |
| | 20 | 33 | | private readonly ITokenValidator[] _validators = validators.ToArray(); |
| | | 34 | | |
| | | 35 | | /// <summary>Validates the request token and, on success, attaches the authenticated user before invoking the next m |
| | | 36 | | /// <param name="context">The current HTTP context.</param> |
| | | 37 | | public async Task InvokeAsync(HttpContext context) |
| | | 38 | | { |
| | 16 | 39 | | if (context.GetEndpoint().AllowsAnonymous() || IsSwaggerRoute(context.Request.Path)) |
| | | 40 | | { |
| | 3 | 41 | | await next(context); |
| | | 42 | | |
| | 3 | 43 | | return; |
| | | 44 | | } |
| | | 45 | | |
| | 13 | 46 | | var token = context.ExtractToken(options.Source, options.CookieName); |
| | | 47 | | |
| | 13 | 48 | | string? lastError = null; |
| | | 49 | | |
| | 47 | 50 | | foreach (var validator in _validators) |
| | | 51 | | { |
| | 14 | 52 | | var (user, error) = await validator.ValidateAsync(token, context); |
| | | 53 | | |
| | 14 | 54 | | if (user is not null) |
| | | 55 | | { |
| | 7 | 56 | | context.SetUser(user); |
| | | 57 | | |
| | 7 | 58 | | await next(context); |
| | | 59 | | |
| | 7 | 60 | | return; |
| | | 61 | | } |
| | | 62 | | |
| | 7 | 63 | | lastError = error; |
| | | 64 | | } |
| | | 65 | | |
| | | 66 | | // Validators still run without a token (the contract allows it, for schemes that read something |
| | | 67 | | // else off the request); the error just says plainly what was missing. |
| | 6 | 68 | | await WriteUnauthorized(context, string.IsNullOrEmpty(token) ? MissingTokenError : lastError); |
| | 16 | 69 | | } |
| | | 70 | | |
| | | 71 | | private static Task WriteUnauthorized(HttpContext context, string? authError) => |
| | 6 | 72 | | context.Response.HasStarted |
| | 6 | 73 | | ? Task.CompletedTask |
| | 6 | 74 | | : context.Response.WriteOutputAsync(StatusCodes.Status401Unauthorized, |
| | 6 | 75 | | ProcessOutput.New.WithError(authError ?? UnauthorizedError)); |
| | | 76 | | |
| | | 77 | | private bool IsSwaggerRoute(PathString path) => |
| | 13 | 78 | | path.StartsWithSegments("/swagger", StringComparison.OrdinalIgnoreCase) && |
| | 13 | 79 | | settings.GetBool(AppSettingsKeys.SwaggerEnabled) is true; |
| | | 80 | | } |