如何使用基于HttpClient和.net4的Rest-client进行身份验证

时间:2011-09-12 11:33:12

标签: .net wcf authentication rest

用HttpClient详细说明了构建一个休息客户端。但我无法弄清楚,也找不到任何关于如何向服务器进行身份验证的示例。我很可能会使用基本的aut,但实际上任何一个例子都会受到赞赏。

在早期版本(在线示例)中,您做到了:

HttpClient client = new HttpClient("http://localhost:8080/ProductService/");
client.TransportSettings.Credentials =
    new System.Net.NetworkCredential("admin", "admin");

但是,版本0.3.0中不再存在TransportSettings属性。

8 个答案:

答案 0 :(得分:85)

所有这些都已过时。最后的方法如下:

var credentials = new NetworkCredential(userName, password);
var handler = new HttpClientHandler { Credentials = credentials };

using (var http = new HttpClient(handler))
{
    // ...
}

答案 1 :(得分:17)

HttpClient库没有进入.Net 4.但是可以在http://nuget.org/List/Packages/HttpClient找到它。但是,在此版本的HttpClient中,身份验证的执行方式不同。

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization 
                   = new AuthenticationHeaderValue("basic","...");

var webRequestHandler = new WebRequestHandler();
CredentialCache creds = new CredentialCache();
creds.Add(new Uri(serverAddress), "basic",
                        new NetworkCredential("user", "password"));
webRequestHandler.Credentials = creds;
var httpClient = new HttpClient(webRequestHandler);

请注意,这个图书馆将在下周更新,并且会有一些细微的变化!

答案 2 :(得分:9)

我尝试了Duncan的建议,但在我的情况下它没有用。我怀疑这是因为我正在集成的服务器,没有发送质询或要求身份验证。它只是拒绝了我的请求,因为我没有提供授权标题。

所以我做了以下事情:

using (var client = new HttpClient())
{
    var encoding = new ASCIIEncoding();
    var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", "username", "password"))));
    client.DefaultRequestHeaders.Authorization = authHeader;
    // Now, the Authorization header will be sent along with every request, containing the username and password.
}

请注意,此处的示例仅适用于Basic authentication

答案 3 :(得分:1)

对于它的价值,没有任何使用HttpClientHandler的工作,至少不是为了尝试对需要服务器管理员凭据的CouchDB API进行经过身份验证的调用。

这对我有用:

using( var client = new HttpClient() )
{
    var byteArray = Encoding.ASCII.GetBytes("MyUSER:MyPASS");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
    ....
}

如答案中所述:

How to use credentials in HttpClient in c#?

答案 4 :(得分:1)

从.NET 4.8,.NET core 3.1和.NET Standard 2.0开始,他们建议同时使用HttpClientCredentialCache。像这样:

const string basicAuthUser = @"myUser";
const string basicAuthPass = @"myPass";
const string host = @"https://my.host.com";
const string path = @"/api";

using (var httpClientHandler = new HttpClientHandler()) {
    httpClientHandler.PreAuthenticate = true;
    httpClientHandler.UseDefaultCredentials = true;

    var basicCredCache = new CredentialCache();
    var basicCredentials = new NetworkCredential(basicAuthUser, basicAuthPass);
    basicCredCache.Add(new Uri(new Uri(host), path), "Basic", basicCredentials);
    httpClientHandler.Credentials = basicCredCache;

    using (var client = new HttpClient(httpClientHandler)) {
        client.BaseAddress = new Uri(host);
        using (var request = new HttpRequestMessage(HttpMethod.Get /*HttpMethod.Post*/, path)) {
            //
            // Send request here
            //
        }
    }
}

编辑:请注意,将HttpClient包装到using中可能会导致高负载下的Socket耗尽。但是,将HttpClient保持为单例可能会导致其他问题,例如过时的DNS问题。从here开始阅读这个漫长的故事。

答案 5 :(得分:0)

我刚刚下载了0.3.0,它确实被删除了。它现在在HttpClientChannel

HttpClient client = new HttpClient(...);
var channel = new HttpClientChannel();
channel.Credentials = new NetworkCredential(...);
client.Channel = channel;

如果未明确指定,则使用默认实例HttpClientChannel

更新: 现在对.Net 4.5无效;请参阅下面的正确答案:https://stackoverflow.com/a/15034995/58391

答案 6 :(得分:0)

我相信这有点旧,但对于寻找更新答案的人来说,我在构建测试服务器时使用了这段代码:

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://myServer/api/Person");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var byteArray = Encoding.ASCII.GetBytes($"{UserName}:{ApiPassword}");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

或者这也有效:

            using (var http = new HttpClient())
            {
                // byteArray is username:password for the server
                var byteArray = Encoding.ASCII.GetBytes("myUserName:myPassword");
                http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                string uri = "http://myServer/api/people" ;
                var response = await http.GetStringAsync(uri);
                List<Person> agencies = JsonConvert.DeserializeObject<List<Person>>(response);
                foreach (Person person in people)
                {
                    listBox1.Items.Add(person.Name);
                }
            }

答案 7 :(得分:-1)

仅在指定DefaultRequestHeaders时有效。它没有任何其他作用。