Skip to content

Commit

Permalink
Fixed Refit's AuthenticationHandler issue. See reactiveui/refit#1761
Browse files Browse the repository at this point in the history
  • Loading branch information
Greenscreener committed Jul 23, 2024
1 parent 58aa429 commit f8cc614
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
26 changes: 26 additions & 0 deletions AuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Net.Http.Headers;

namespace matrix_dotnet;

// <summary>
// This is taken directly from Refit's source, because the class is private
// See <see href="https://github.com/reactiveui/refit/issues/1761">
// </summary>
class AuthenticatedHttpClientHandler : DelegatingHandler {
readonly Func<HttpRequestMessage, CancellationToken, Task<string>> getToken;

public AuthenticatedHttpClientHandler(Func<HttpRequestMessage, CancellationToken, Task<string>> getToken, HttpMessageHandler? innerHandler = null) : base(innerHandler ?? new HttpClientHandler()) {
this.getToken = getToken ?? throw new ArgumentNullException(nameof(getToken));
}

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
// See if the request has an authorize header
var auth = request.Headers.Authorization;
if (auth != null) {
var token = await getToken(request, cancellationToken).ConfigureAwait(false);
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}

return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
10 changes: 5 additions & 5 deletions MatrixClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,19 @@ public MatrixClient(Uri homeserver, ILogger? logger = null) {
apiUrlB.Path = "/_matrix/client/v3";

HttpClient client;
if (Logger is not null) { // FIXME
client = new HttpClient(new HttpLoggingHandler(Logger));
if (Logger is not null) {
client = new HttpClient(new HttpLoggingHandler(Logger, new AuthenticatedHttpClientHandler(GetAccessToken)));
} else {
client = new HttpClient();
client = new HttpClient(new AuthenticatedHttpClientHandler(GetAccessToken));
}
client.BaseAddress = apiUrlB.Uri;

RefitSettings = new RefitSettings {
ExceptionFactory = ExceptionFactory,
AuthorizationHeaderValueGetter = GetAccessToken // FIXME: This conflicts with having a custom handler, which is useful for logging
AuthorizationHeaderValueGetter = GetAccessToken
};

Api = RestService.For<IMatrixApi>(apiUrlB.Uri.ToString(), RefitSettings);
Api = RestService.For<IMatrixApi>(client, RefitSettings);
}

private void UpdateExpiresAt(int? expiresInMs) {
Expand Down

0 comments on commit f8cc614

Please sign in to comment.