Flurl has methods for doing OAuth and Basic authentication:
await url.WithBasicAuth("username", "password").GetJsonAsync();
await url.WithOAuthBearerToken("mytoken").GetJsonAsync();
but how do I do Windows authentication using the currently logged in user? The HttpClientHandler that Flurl is built on top of has a property UseDefaultCredentials but I don't know how to utilize that within Flurl.
var httpClient = new HttpClient(new HttpClientHandler()
{
UseDefaultCredentials = true
});
Flurl intelligently reuses the HttpClientHandler for each domain, so you don't want to set the UseDefaultCredentials each time it runs. Instead, you can modify the HttpClientFactory to return one that's configured to UseDefaultCredentials.
public class UseDefaultCredentialsClientFactory : DefaultHttpClientFactory
{
public override HttpMessageHandler CreateMessageHandler()
{
return new HttpClientHandler { UseDefaultCredentials = true };
}
}
Then you need to tell Flurl to use this factory for the domains you want to use Windows authentication for.
public static class FlurlConfiguration
{
public static void ConfigureDomainForDefaultCredentials(string url)
{
FlurlHttp.ConfigureClient(url, cli =>
cli.Settings.HttpClientFactory = new UseDefaultCredentialsClientFactory());
}
}
Then you simply need to call this once on startup for each domain. For ASP.NET, the Application_Start method in your global application class is a good place for it.
FlurlConfiguration.ConfigureDomainForDefaultCredentials("https://example.com");
FlurlConfiguration.ConfigureDomainForDefaultCredentials("http://services.example.com");
Credit goes to Todd Menier for explaining this to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With