Files
oed/api/OED.Api/Infrastructure/Esi/EsiAuthHandler.cs

37 lines
1.2 KiB
C#

using System.Net.Http.Headers;
using OED.Api.Core.Interfaces.Services;
namespace OED.Api.Infrastructure.Esi;
public class EsiAuthHandler(
ITokenStore tokenStore,
IEsiTokenRefreshService refreshService,
IHttpContextAccessor httpContextAccessor
) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var characterId = GetCharacterIdFromSession();
if (characterId is null)
return await base.SendAsync(request, cancellationToken);
var accessToken = await tokenStore.GetAccessTokenAsync(characterId.Value);
if (accessToken is null)
accessToken = await refreshService.RefreshAsync(characterId.Value);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return await base.SendAsync(request, cancellationToken);
}
private long? GetCharacterIdFromSession()
{
var context = httpContextAccessor.HttpContext;
// CharacterId is set on the HttpContext by session middleware
return context?.Items["CharacterId"] as long?;
}
}