Description
openedon Mar 18, 2021
What should we add or change to make your life better?
Please add a sample or documentation for using a DelegatingHandler with ProxyHttpClient.
DelegatingHandler was mentioned in #137, but I can't find any further information.
Why is this important to you?
I have a Single-Page Application (in Blazor) with a Backend-For-Frontend (BFF). I am using cookie authentication on the BFF and all requests from the SPA get forwarded by the BFF to an API that expects a bearer token.
Currently, I am using ProxyKit together with the IdentityModel.AspNetCore package.
The BFF takes the token that is stored in the cookie and adds it to the authorization header. If the token is expired, it gets automatically renewed. This is done via the UserAccessTokenHandler
.
In ProxyKit it is very easy to configure it:
services.AddAccessTokenManagement();
services.AddProxy((clientBuilder) =>
{
// adds the access token to all forwarded requests,
// and refreshes the access token if needed.
clientBuilder.AddUserAccessTokenHandler();
});
I understand that it's not recommended to use the HttpClient
because it buffers responses by default. But it would be nice to have a similar way to register delegating handlers.
Another option would be to rewrite the logic and use a transformation instead of the delegating handler. But then I would have to maintain it by myself and I think it's better to reuse what's already there and don't reinvent it.
So, for now, I implemented a custom IProxyHttpClientFactory
, but I am not sure if this is the preferred way of doing it:
public class UserAccessTokenProxyHttpClientFactory : IProxyHttpClientFactory
{
private readonly UserAccessTokenHandler _userAccessTokenHandler;
public UserAccessTokenProxyHttpClientFactory(UserAccessTokenHandler userAccessTokenHandler)
{
_userAccessTokenHandler = userAccessTokenHandler;
var socketsHttpHandler = new SocketsHttpHandler
{
UseProxy = false,
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.None,
UseCookies = false
};
_userAccessTokenHandler.InnerHandler = socketsHttpHandler;
}
public HttpMessageInvoker CreateClient(ProxyHttpClientContext context)
{
if (context.OldClient != null && context.NewOptions == context.OldOptions)
{
return context.OldClient;
}
return new HttpMessageInvoker(_userAccessTokenHandler, disposeHandler: false);
}
}
My full sample can be found here: https://github.com/berhir/BlazorWebAssemblyCookieAuth