JwtForwardingHandler.cs
1,726 bytes
| 1 | using System.Net.Http.Headers; |
|---|---|
| 2 | |
| 3 | namespace SplitApp.WebApp.Application.UsersService; |
| 4 | |
| 5 | /// <summary> |
| 6 | /// DelegatingHandler used by the <see cref="IUsersServiceClient"/> typed HttpClient. |
| 7 | /// Forwards the inbound JWT (cookie or Authorization header) on the outbound call so |
| 8 | /// the Users service can enforce <c>[Authorize]</c> + role checks on admin endpoints. |
| 9 | /// </summary> |
| 10 | public class JwtForwardingHandler : DelegatingHandler |
| 11 | { |
| 12 | private readonly IHttpContextAccessor _httpContext; |
| 13 | |
| 14 | public JwtForwardingHandler(IHttpContextAccessor httpContext) => _httpContext = httpContext; |
| 15 | |
| 16 | protected override Task<HttpResponseMessage> SendAsync( |
| 17 | HttpRequestMessage request, CancellationToken cancellationToken) |
| 18 | { |
| 19 | if (request.Headers.Authorization is null) |
| 20 | { |
| 21 | var ctx = _httpContext.HttpContext; |
| 22 | string? token = null; |
| 23 | |
| 24 | if (ctx is not null) |
| 25 | { |
| 26 | // 1) Authorization header from the inbound request |
| 27 | if (ctx.Request.Headers.TryGetValue("Authorization", out var authHdr)) |
| 28 | { |
| 29 | var value = authHdr.ToString(); |
| 30 | if (value.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) |
| 31 | { |
| 32 | token = value["Bearer ".Length..]; |
| 33 | } |
| 34 | } |
| 35 | // 2) Fallback: jwt cookie (MVC views path) |
| 36 | token ??= ctx.Request.Cookies["jwt"]; |
| 37 | } |
| 38 | |
| 39 | if (!string.IsNullOrEmpty(token)) |
| 40 | { |
| 41 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | return base.SendAsync(request, cancellationToken); |
| 46 | } |
| 47 | } |
| 48 | |