Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Windows Authentication with the Flurl library?

Tags:

c#

flurl

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
});
like image 994
mason Avatar asked Sep 15 '18 17:09

mason


1 Answers

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.

like image 195
mason Avatar answered Oct 21 '22 04:10

mason