dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.22k stars 4.72k forks source link

Handle authorization tokens with a client handler #36551

Open rynowak opened 6 years ago

rynowak commented 6 years ago

This item tracks some support for providing a client handler that will do authentication for you and handle token refreshes transparently. Any mechanism that requires user-intervention during the authentication process is out of scope.

This is a future looking tracking item and is not planned for 2.1.0.

darrelmiller commented 6 years ago

Can it handle any arbitrary auth scheme like CredenticalCache used to? Something like https://github.com/tavis-software/Tavis.Auth/blob/master/src/Auth/AuthMessageHandler.cs ?

rynowak commented 6 years ago

Open to suggestions. We're not going to start working on this for a little while.

johnkors commented 6 years ago

I think you can plug any handler you want, for example the AccessTokenHandler from IdentityModel, which handles refreshes..?

Configuring the HttpClientFactoryOptions:

options.HttpMessageHandlerBuilderActions.Add(b =>
{
   b.PrimaryHandler = new AccessTokenHandler(tokenEndpoint, clientId, clientSecret);
});
poke commented 6 years ago

IdentityModel 3.7 adds AccessTokenDelegatingHandler and RefreshTokenDelegatingHandler which work nicely for this when added as AdditionalHandlers.

xneg commented 6 years ago

How do you want to link asynchronous token retrieval with synchronous factory.CreateClient()? Do you want to extend IHttpClientFactory contract adding something like CreateClientAsync()?

martincostello commented 6 years ago

The token creation would happen asynchronously as part of the HTTP requests, not as part of the client creation.

xneg commented 6 years ago

@martincostello got you, thanks! Just trying to create something similar using current factory realization...

rggammon commented 5 years ago

One idea - if there were something like a IHttpClientFactory.CreateClient() that accepted additional DelegatingHandler's for the specific client (in this case, a handler for handling auth / tokens), that would give me the ability to initialize the auth handler from the code creating the http client.

Similar to HttpClientFactory.Create() in System.Net.Http.Formatting.

davidfowl commented 3 years ago

I'm not sure what needs to be done here to HttpClientFactory itself.

gklittlejohn commented 2 years ago

Is it valid to use IHttpMessageHandlerFactory for this type of scenario i.e. for allowing additional handlers for access tokens to be created at runtime?:

IHttpMessageHandlerFactory messageHandlerFactory = services.GetRequiredService<IHttpMessageHandlerFactory>();
HttpMessageHandler factoryHandler = factory.CreateHandler();
HttpClient httpClient = new HttpClient(new AccessTokenHandler(factoryHandler), disposeHandler: false)