I'm trying to call the Shopware REST API from c#. Shopware has documentation for calling the API using curl, and mostly I can convert this to c# and HttpClient, but for some options I just don't know what headers to set:
The Shop is behind a basic htaccess-auth and has the Shopware auth using an apikey. My code so far:
var handler = new System.Net.Http.HttpClientHandler { Credentials = new NetworkCredential(htaccessUsername, htaccessPassword) });
var client = new System.Net.Http.HttpClient(handler);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl + "orders?limit=20"))
{
var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{apiKey}"));
var authorizationKey = "Basic" + " " + encodedStr;
requestMessage.Headers.Add("Authorization", authorizationKey);
// curl_setopt($this->cURL, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($this->cURL, CURLOPT_FOLLOWLOCATION, false);
// curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
// curl_setopt(
// $this->cURL,
// CURLOPT_HTTPHEADER,
// ['Content-Type: application/json; charset=utf-8']
// );
using (var responseMessage = await client.SendAsync(requestMessage))
{
var data = await responseMessage.Content.ReadAsStringAsync();
System.Diagnostics.Trace.WriteLine(data);
}
}
Basic htaccess auth is working, but the Shopware auth does fail with the following response in data:
"{\"success\":false,\"message\":\"Invalid or missing auth\"}"
I guess I Need to somehow achieve curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
in c#, but I found no clue how to convert These curl options to a header.
Any help?
Looks like the answer for you is here:
var credCache = new CredentialCache();
var basicCred = new NetworkCredential(htaccessUsername, htaccessPassword);
var digestCred = new NetworkCredential(username, apiKey);
credCache.Add(new Uri("http://.com/"), "Basic", basicCred);
credCache.Add(new Uri("http://.com/"), "Digest", digestCred);
var httpClient = new HttpClient(new HttpClientHandler { Credentials = credCache });