在 C# 中具有授权的 HTTPS 客户端

Https client with authorization in C#

我正在尝试用 C# 创建一个 https 客户端。

我的 HTTP 客户端运行良好,我将其更改为使用 HTTPS。但不幸的是授权有问题(服务器使用OAuth 2)。

我的程序向服务器发送请求并获取令牌。但是它无法从服务器获取或发送任何数据。

服务器与其他客户端一起工作正常,所以这不是它的错。

这是导致问题的一段代码。我知道,因为当我在服务器上评论授权时,数据被发送(一切都很好)。

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
        "Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
         string.Format("Authorization: {0}", token))));

这是整个函数,应该发送数据:

WebRequestHandler handler = new WebRequestHandler();
X509Certificate certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
var client = new HttpClient(handler);

string uri = "https://192.168.0.10:8443/data";

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
     string.Format("Authorization: {0}", token))));

client.BaseAddress = new Uri(uri);

var parameters = new Dictionary<string, string>();
parameters["name"] = name;
parameters["surname"] = surname;

JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(parameters);

System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var response = client.PostAsync(uri, new StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;

Console.WriteLine((response.StatusCode.ToString()));
string resultContent = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);

我想我在 header 中遗漏了一些东西,但在文档中找不到任何相关信息。 这是一个难题,因此非常感谢任何建议。

您不应在 AuthenticationHeaderValue 的参数中包含 HTTP header 名称 ("Authorization: ")。设置 Authorization 属性 会将 header 添加到请求中。

此外,对于 OAuth 2,您可能希望使用 "Bearer" 作为方案,而不是使用 base64 编码 token

因此,这样的事情应该有效:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);