- Remove SendWithRefreshAsync method from AuthServiceBase (now dead code) - Replace all 15 SendWithRefreshAsync call sites in 7 services with direct Client.XxxAsync calls - Remove unused using System.Net from AuthServiceBase - Update AGENTS.md to document JwtTokenRefresher as the sole token refresh mechanism
52 lines
2.2 KiB
C#
52 lines
2.2 KiB
C#
using Microsoft.Extensions.Options;
|
|
|
|
namespace MilkStream.Client.Services;
|
|
|
|
/// <summary>
|
|
/// Abstract class for services that require authentication. Builds on top of ServiceBase.
|
|
/// </summary>
|
|
public abstract class AuthServiceBase : ServiceBase {
|
|
/// <summary>
|
|
/// Gets the HTTP client for making API requests.
|
|
/// </summary>
|
|
protected override HttpClient Client { get; init; }
|
|
|
|
/// <summary>
|
|
/// Gets the login service for authentication operations.
|
|
/// </summary>
|
|
protected LoginService LoginService { get; }
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="AuthServiceBase"/> class with the specified options, HTTP client factory, and login service connection.
|
|
/// </summary>
|
|
/// <param name="options">Service configuration options.</param>
|
|
/// <param name="httpClientFactory">Factory for creating HTTP clients.</param>
|
|
/// <param name="loginService">The login service for authentication.</param>
|
|
/// <param name="logger">Logger instance.</param>
|
|
protected AuthServiceBase(
|
|
IOptions<ServiceOptions> options,
|
|
IHttpClientFactory httpClientFactory,
|
|
LoginService loginService,
|
|
ILogger logger
|
|
) : base(options, httpClientFactory, logger) {
|
|
LoginService = loginService;
|
|
Client = httpClientFactory.CreateClient("MilkstreamClient");
|
|
Client.BaseAddress = new Uri(options.Value.BaseUrl);
|
|
// Subscribe to the AuthInfoChanged event to set the authorization header when the auth info changes.
|
|
loginService.AuthInfoChanged += SetAuthorizationHeader;
|
|
// Set the initial authorization header and base address.
|
|
SetAuthorizationHeader(null, loginService.AuthInfo);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handles the AuthInfoChanged event to update the Authorization header for the HTTP client.
|
|
/// </summary>
|
|
/// <param name="sender"></param>
|
|
/// <param name="authInfo"></param>
|
|
protected virtual void SetAuthorizationHeader(object? sender, AuthInfo? authInfo) {
|
|
if (authInfo == null) //no authentication available = logged out
|
|
Client.DefaultRequestHeaders.Authorization = null;
|
|
else Client.DefaultRequestHeaders.Authorization = new("Bearer", authInfo.Token);
|
|
}
|
|
}
|