How do I use Windows Authentication with the Flurl library?

一笑奈何 提交于 2020-03-12 19:01:48

问题


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

回答1:


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.




回答2:


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

 ((HttpClientHandler)url.Client.HttpMessageHandler).Credentials = new NetworkCredential(userName, password);


来源:https://stackoverflow.com/questions/52347213/how-do-i-use-windows-authentication-with-the-flurl-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!