如何使用HttpClient发布身份验证

时间:2015-06-16 04:36:42

标签: c# .net 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

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

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

通常情况下,我能够完全获得GET和POST,但最让我失望的是如何设置auth的东西(client-id和client-secret)

3 个答案:

答案 0 :(得分:20)

尝试将您的凭据直接放入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);
}

答案 1 :(得分:18)

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

您应该使用StringContent,而不是使用FormUrlEncodedContent,如下所示:

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

答案 2 :(得分:3)

BasicAuthenticationHeaderValue

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