Skip to content

Commit f8cc614

Browse files
committed
Fixed Refit's AuthenticationHandler issue. See reactiveui/refit#1761
1 parent 58aa429 commit f8cc614

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

AuthenticationHandler.cs

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System.Net.Http.Headers;
2+
3+
namespace matrix_dotnet;
4+
5+
// <summary>
6+
// This is taken directly from Refit's source, because the class is private
7+
// See <see href="https://github.com/reactiveui/refit/issues/1761">
8+
// </summary>
9+
class AuthenticatedHttpClientHandler : DelegatingHandler {
10+
readonly Func<HttpRequestMessage, CancellationToken, Task<string>> getToken;
11+
12+
public AuthenticatedHttpClientHandler(Func<HttpRequestMessage, CancellationToken, Task<string>> getToken, HttpMessageHandler? innerHandler = null) : base(innerHandler ?? new HttpClientHandler()) {
13+
this.getToken = getToken ?? throw new ArgumentNullException(nameof(getToken));
14+
}
15+
16+
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
17+
// See if the request has an authorize header
18+
var auth = request.Headers.Authorization;
19+
if (auth != null) {
20+
var token = await getToken(request, cancellationToken).ConfigureAwait(false);
21+
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
22+
}
23+
24+
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
25+
}
26+
}

MatrixClient.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -76,19 +76,19 @@ public MatrixClient(Uri homeserver, ILogger? logger = null) {
7676
apiUrlB.Path = "/_matrix/client/v3";
7777

7878
HttpClient client;
79-
if (Logger is not null) { // FIXME
80-
client = new HttpClient(new HttpLoggingHandler(Logger));
79+
if (Logger is not null) {
80+
client = new HttpClient(new HttpLoggingHandler(Logger, new AuthenticatedHttpClientHandler(GetAccessToken)));
8181
} else {
82-
client = new HttpClient();
82+
client = new HttpClient(new AuthenticatedHttpClientHandler(GetAccessToken));
8383
}
8484
client.BaseAddress = apiUrlB.Uri;
8585

8686
RefitSettings = new RefitSettings {
8787
ExceptionFactory = ExceptionFactory,
88-
AuthorizationHeaderValueGetter = GetAccessToken // FIXME: This conflicts with having a custom handler, which is useful for logging
88+
AuthorizationHeaderValueGetter = GetAccessToken
8989
};
9090

91-
Api = RestService.For<IMatrixApi>(apiUrlB.Uri.ToString(), RefitSettings);
91+
Api = RestService.For<IMatrixApi>(client, RefitSettings);
9292
}
9393

9494
private void UpdateExpiresAt(int? expiresInMs) {

0 commit comments

Comments
 (0)