| | | 1 | | using System.Net.Http.Headers; |
| | | 2 | | using ArturRios.Util.WebApi.Security.Enums; |
| | | 3 | | using Microsoft.AspNetCore.Http; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Util.WebApi.Security.Authentication; |
| | | 6 | | |
| | | 7 | | /// <summary>Reads the raw authentication token from an <see cref="HttpContext"/> according to a <see cref="TokenSource" |
| | | 8 | | public static class TokenExtractor |
| | | 9 | | { |
| | | 10 | | /// <summary>Extracts the token from the header, the named cookie, or either (header first), returning <see cref="st |
| | | 11 | | /// <param name="context">The current HTTP context.</param> |
| | | 12 | | /// <param name="source">Where to read the token from.</param> |
| | | 13 | | /// <param name="cookieName">The cookie name used when <paramref name="source"/> is <see cref="TokenSource.Cookie"/> |
| | | 14 | | public static string Extract(HttpContext context, TokenSource source, string cookieName) |
| | 15 | 15 | | { |
| | 15 | 16 | | ArgumentNullException.ThrowIfNull(context); |
| | | 17 | | |
| | 15 | 18 | | return source switch |
| | 15 | 19 | | { |
| | 8 | 20 | | TokenSource.Header => FromHeader(context), |
| | 4 | 21 | | TokenSource.Cookie => FromCookie(context, cookieName), |
| | 3 | 22 | | TokenSource.Either => FromHeader(context) is { Length: > 0 } header ? header : FromCookie(context, cookieNam |
| | 0 | 23 | | _ => string.Empty |
| | 15 | 24 | | }; |
| | 15 | 25 | | } |
| | | 26 | | |
| | | 27 | | private static string FromHeader(HttpContext context) |
| | 11 | 28 | | { |
| | 11 | 29 | | var header = context.Request.Headers.Authorization.FirstOrDefault(); |
| | | 30 | | |
| | 11 | 31 | | if (string.IsNullOrWhiteSpace(header) || !AuthenticationHeaderValue.TryParse(header, out var parsed) || |
| | 11 | 32 | | !string.Equals(parsed.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase) || |
| | 11 | 33 | | string.IsNullOrWhiteSpace(parsed.Parameter)) |
| | 4 | 34 | | { |
| | 4 | 35 | | return string.Empty; |
| | | 36 | | } |
| | | 37 | | |
| | 7 | 38 | | return parsed.Parameter.Trim(); |
| | 11 | 39 | | } |
| | | 40 | | |
| | | 41 | | private static string FromCookie(HttpContext context, string cookieName) |
| | 6 | 42 | | { |
| | 6 | 43 | | var value = context.Request.Cookies[cookieName]; |
| | | 44 | | |
| | 6 | 45 | | return string.IsNullOrWhiteSpace(value) ? string.Empty : value.Trim(); |
| | 6 | 46 | | } |
| | | 47 | | } |