How to use HttpClient to Post with Authentication

后端 未结 2 2049
长发绾君心
长发绾君心 2020-12-15 03:46

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

curl -X POST http://www.somehosturl.com \\
     -u :

        
相关标签:
2条回答
  • 2020-12-15 04:04

    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);
    
    0 讨论(0)
  • 2020-12-15 04:12

    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);
    }
    
    0 讨论(0)
提交回复
热议问题