如何将Windows身份验证与Flurl库一起使用? [英] How do I use Windows Authentication with the Flurl library?

查看:100
本文介绍了如何将Windows身份验证与Flurl库一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flurl 具有执行OAuth和基本身份验证的方法:

Flurl has methods for doing OAuth and Basic authentication:

await url.WithBasicAuth("username", "password").GetJsonAsync();
await url.WithOAuthBearerToken("mytoken").GetJsonAsync();

但是如何使用当前登录的用户执行Windows身份验证?构建在Flurl之上的HttpClientHandler具有属性UseDefaultCredentials,但是我不知道如何在Flurl中使用它.

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为每个域智能地重用HttpClientHandler,因此您不想每次运行时都设置UseDefaultCredentials.相反,您可以修改HttpClientFactory以返回配置为UseDefaultCredentials的一个.

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

然后,您需要告诉Flurl将要用于Windows身份验证的域使用此工厂.

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

然后,您只需要在启动时为每个域调用一次即可.对于ASP.NET,全局应用程序类中的Application_Start方法是一个不错的选择.

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

托德·梅尼尔(Todd Menier)向我解释这件事.

这篇关于如何将Windows身份验证与Flurl库一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆