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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7387205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:53:20  来源:igfitidea点击:

How to authenticate with Rest-client based on HttpClient and .net4

.netwcfauthenticationrest

提问by Tomas

Been elaborating a bit with HttpClient for building a rest client. But I can't figure out, nor find any examples on how to authenticate towards the server. Most likely I will use basic aut, but really any example would be appreciated.

使用 HttpClient 详细阐述了构建休息客户端。但我无法弄清楚,也找不到任何关于如何向服务器进行身份验证的示例。我很可能会使用基本的 aut,但实际上任何示例都将不胜感激。

In earlier versions (which has examples online) you did:

在早期版本(有在线示例)中,您执行了以下操作:

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

However the TransportSettingsproperty no longer exists in version 0.3.0.

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

回答by Duncan Smart

All these are out of date. The final way to do it is as follows:

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

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

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

回答by Darrel Miller

The HttpClient library did not make it into .Net 4. However it is available here http://nuget.org/List/Packages/HttpClient. However, authentication is done differently in this version of HttpClient.

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

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

or

或者

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

And be warned, this library is going to get updated next week and there are minor breaking changes!

请注意,这个库将在下周更新,并且会有一些小的突破性变化!

回答by René

I tried Duncan's suggestion, but it didn't work in my case. I suspect it was because the server I was integrating with, didn't send a challenge or ask for authentication. It just refused my requests, because I didn't supply an Authorizationheader.

我尝试了邓肯的建议,但在我的情况下不起作用。我怀疑这是因为我与之集成的服务器没有发送质询或要求进行身份验证。它只是拒绝了我的请求,因为我没有提供Authorization标头。

So I instead did the following:

所以我做了以下事情:

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

Notice that the example here only works with Basic authentication.

请注意,此处的示例仅适用于基本身份验证

回答by ChrisCW

For what it is worth, nothing using HttpClientHandler worked, at least not for trying to make an authenticated call to the CouchDB API that requires server admin credentials.

就其价值而言,使用 HttpClientHandler 没有任何效果,至少不会尝试对需要服务器管理员凭据的 CouchDB API 进行经过身份验证的调用。

This worked for me:

这对我有用:

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

As outlined in the answer here:

如此处的答案所述:

How to use credentials in HttpClient in c#?

如何在 c# 中的 HttpClient 中使用凭据?

回答by GaryP

I believe this is a bit old, but for anyone looking for an updated answer, I used this code when I built my test server:

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

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

Or this works too:

或者这也有效:

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

回答by TheCodeKing

I just downloaded 0.3.0 it has indeed be removed. It's now on HttpClientChannel

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

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

If not explicitly specified it uses a default instance of HttpClientChannel.

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

UPDATE:this is now invalid for .Net 4.5; see correct answer below: https://stackoverflow.com/a/15034995/58391

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