Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HttpClient to Post with Authentication

I am trying to do the following curl (which works for me) in C# using HttpClient.

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:

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&[email protected]&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)

like image 331
Jesse Avatar asked Jun 16 '15 04:06

Jesse


People also ask

How do I add Auth header to HttpClient?

using (var client = new HttpClient()) { var url = "https://www.theidentityhub.com/{tenant}/api/identity/v1"; client. DefaultRequestHeaders. Add("Authorization", "Bearer " + accessToken); var response = await client.


2 Answers

First you have to set the Authorization-Header with your <clientid> and <clientsecret>.

Instead of using StringContent you should use FormUrlEncodedContent as shown below:

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); 
like image 51
Alexander Zeitler Avatar answered Sep 28 '22 10:09

Alexander Zeitler


Try to place your credentials directly into the headers property of 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);
}
like image 23
n.yakovenko Avatar answered Sep 28 '22 08:09

n.yakovenko