简体   繁体   English

如何使用 HttpClient 进行身份验证发布

[英]How to use HttpClient to Post with Authentication

I am trying to do the following curl (which works for me) in C# using HttpClient.我正在尝试使用 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

The C# Code: 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;
    }

When executed, just crashes out, doesnt even catch the exception执行时,只是崩溃,甚至没有捕获异常

Normally I am able to GET and POST perfectly fine, but whats throwing me off is how to set the auth stuff (client-id and client-secret)通常我能够 GET 和 POST 非常好,但让我失望的是如何设置身份验证的东西(客户端 ID 和客户端机密)

First you have to set the Authorization -Header with your <clientid> and <clientsecret> .首先,您必须使用<clientid><clientsecret>设置Authorization -Header。

Instead of using StringContent you should use FormUrlEncodedContent as shown below:您应该使用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);

Try to place your credentials directly into the headers property of HttpClient.尝试将您的凭据直接放入 HttpClient 的 headers 属性中。

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

See BasicAuthenticationHeaderValue请参阅BasicAuthenticationHeaderValue

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM