How do I use Windows Authentication with the Flurl

2020-02-23 04:15发布

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
});

标签: c# flurl
2条回答
再贱就再见
2楼-- · 2020-02-23 04:20

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.

查看更多
Ridiculous、
3楼-- · 2020-02-23 04:27

If it is still relevant. You can set credentials, something like this

 ((HttpClientHandler)url.Client.HttpMessageHandler).Credentials = new NetworkCredential(userName, password);
查看更多
登录 后发表回答