File size: 1,120 Bytes
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System;
using System.Net.Http;

namespace TaskTrackingSystem.WebApp;

public class AuthorizedHttpClientFactory : IHttpClientFactory
{
    private readonly IHttpClientFactory _innerFactory;
    private readonly UserSessionState _sessionState;

    public AuthorizedHttpClientFactory(IHttpClientFactory innerFactory, UserSessionState sessionState)
    {
        _innerFactory = innerFactory;
        _sessionState = sessionState;
    }

    public HttpClient CreateClient(string name)
    {
        var client = _innerFactory.CreateClient(name);
        if (name == "WebApi")
        {
            try
            {
                var token = _sessionState.Token;
                if (!string.IsNullOrEmpty(token))
                {
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AuthorizedHttpClientFactory] Error attaching bearer token: {ex.Message}");
            }
        }
        return client;
    }
}