-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAuthenticatedHttpMessageHandler.cs
More file actions
54 lines (48 loc) · 1.83 KB
/
AuthenticatedHttpMessageHandler.cs
File metadata and controls
54 lines (48 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace SentenceStudio.Services;
/// <summary>
/// Delegating handler that attaches a Bearer token to outgoing requests.
/// Attempts token acquisition unconditionally. If it returns null, the
/// request proceeds without an Authorization header so the server's
/// DevAuthHandler handles unauthenticated requests during development.
/// </summary>
public class AuthenticatedHttpMessageHandler : DelegatingHandler
{
private readonly string[] _defaultScopes;
private readonly IAuthService _authService;
private readonly ILogger<AuthenticatedHttpMessageHandler> _logger;
public AuthenticatedHttpMessageHandler(
IAuthService authService,
IConfiguration configuration,
ILogger<AuthenticatedHttpMessageHandler> logger)
{
_authService = authService;
_logger = logger;
_defaultScopes = configuration.GetSection("AzureAd:Scopes").Get<string[]>()
?? throw new InvalidOperationException(
"AzureAd:Scopes must be configured.");
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var token = await _authService.GetAccessTokenAsync(_defaultScopes);
if (!string.IsNullOrEmpty(token))
{
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to attach Bearer token; proceeding without auth");
}
return await base.SendAsync(request, cancellationToken);
}
}