如何使用 HttpClient 通过身份验证发布

本文关键字:身份验证 何使用 HttpClient | 更新日期: 2023-09-27 17:56:29

我正在尝试使用 HttpClient 在 C# 中执行以下 curl(对我有用)。

curl -X POST http://www.somehosturl.com '
     -u <client-id>:<client-secret> '
     -d 'grant_type=password' '
     -d 'username=<email>' '
     -d 'password=<password>' '
     -d 'scope=all

C# 代码:

HttpClientHandler handler = new HttpClientHandler { Credentials = new  
            System.Net.NetworkCredential ("my_client_id", "my_client_secret")
    };

    try
    {
        using(var httpClient = new HttpClient(handler))
        {
            var activationUrl = "www.somehosturl.com";
            var postData = "grant_type=password&username=myemail@myemail.com&password=mypass&scope=all";
            var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
            var response = await httpClient.PostAsync(activationUrl, content);
            if(!response.IsSuccessStatusCode)
                return null;
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }
    catch(Exception)
    {
        return null;
    }

执行时,只是崩溃,甚至没有捕获异常

通常我能够很好地获取和发布,但是让我失望的是如何设置身份验证的东西(客户端ID和客户端机密)

如何使用 HttpClient 通过身份验证发布

首先,您必须使用<clientid><clientsecret>设置Authorization -Header。

您应该使用如下所示

FormUrlEncodedContent而不是使用StringContent

var client = new HttpClient();
client.BaseAddress = new Uri("http://myserver");
var request = new HttpRequestMessage(HttpMethod.Post, "/path");
var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("grant_type", "password"));
formData.Add(new KeyValuePair<string, string>("username", "<email>"));
formData.Add(new KeyValuePair<string, string>("password", "<password>"));
formData.Add(new KeyValuePair<string, string>("scope", "all"));
request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);

尝试将凭据直接放入 HttpClient 的标头属性中。

using (var client = new HttpClient()) {
       var byteArray = Encoding.ASCII.GetBytes("my_client_id:my_client_secret");
       var header = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray));
       client.DefaultRequestHeaders.Authorization = header;
       return await client.GetStringAsync(uri);
}

请参阅 BasicAuthenticationHeaderValue

httpClient.DefaultRequestHeaders.Authorization
    = new BasicAuthenticationHeaderValue("login", "password");

或者使用来自 IdentityModel 的扩展:

<PackageReference Include="IdentityModel" Version="4.0.0" />
var client = new HttpClient();
client.SetBasicAuthentication(login, password);
client.SetBearerToken(token);