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 });
Related
I am using Botframework adaptive dialog template (c#). I already obtained a token from a HttpRequest and saved it as a conversation state property conversation.token, now I am trying to use this token to make another API call with HttpRequest. But from the official document of HttpRequest Class, it seems there is no options to add the authentication token. I tried to add the token in the Headers, but did not work, it showed 401 Unauthorized error. How should the authorization be handled in HttpRequest in adaptive dialog?
new HttpRequest()
{
Url = "http://example.com/json",
ResultProperty = "conversation.httpResponse",
Method = HttpRequest.HttpMethod.GET,
ResponseType = HttpRequest.ResponseTypes.Json,
Headers = new Dictionary<string, AdaptiveExpressions.Properties.StringExpression>()
{
{"Authorization", "Bearer ${conversation.token.content.token}"},
},
},
new SendActivity("${conversation.httpResponse}"),
Instead of using HttpRequest, I made the API call inside CodeAction with custom code.
First make a POST request to get the token, then make a GET request to call the main API. In the GET request, the authorization can be added in this way: client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);.
new CodeAction(async (dc, options) =>
{
var my_jsondata = new
{
Username = "username",
Password = "password"
};
var json = JsonConvert.SerializeObject(my_jsondata);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var Tokenurl = "https://example.com/token?HTTP/1.1";
using var Tokenclient = new HttpClient();
var Tokenresponse = await Tokenclient.PostAsync(Tokenurl, data);
string Toeknresult = Tokenresponse.Content.ReadAsStringAsync().Result;
var Tokenjo = JObject.Parse(Tokenresult);
using var client = new HttpClient();
var url = "https://example.com/mainapi?HTTP/1.1";
var accessToken = Tokenjo["token"];
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetAsync(url);
string result = response.Content.ReadAsStringAsync().Result;
dc.State.SetValue("conversation.httpresponse", response);
dc.State.SetValue("conversation.result", result);
return await dc.EndDialogAsync();
}),
I'm experiencing an intermittent problem with our SharePoint 2010 REST API. I have a .Net Core Console application that makes a series of calls to SharePoint List Endpoints to get a JSON response. My problem is that at random times, the API response is an error page:
A relative URI cannot be created because the 'uriString' parameter
represents an absolute URI.http://www.example.com/somefolder/file.svc
Is there a problem with my HTTPClient configuration? Is there a configuration setting that I can toggle in SharePoint to prevent the error or more reliable?
var uri = new Uri("http://www.example.com/");
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient Client = new HttpClient(handler);
Client.BaseAddress = new Uri("http://www.example.com/sharepoint/path/ListData.svc/");
// Make the list request
var result = await Client.GetAsync("MySharePointList");
To get the list items, the REST API URI like below.
http://sp2010/_vti_bin/ListData.svc/listname
Modify the code as below.
var siteUrl = "http://www.example.com/";
var listName = "MySharePointList";
var uri = new Uri(siteUrl);
var credential = new NetworkCredential("username", "password", "domain");
var credentialsCache = new CredentialCache { { uri, "NTLM", credential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(uri, "/_vti_bin/ListData.svc");
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
var requestURL = siteUrl + "/_vti_bin/ListData.svc/" + listName;
// Make the list request
var result = client.GetAsync(requestURL).Result;
var items= result.Content.ReadAsStringAsync();
I'm trying to make a simple request to the Basecamp API, I'm following the instructions provided adding in a sample user agent and my credentials yet I keep getting a 403 Forbidden response back.
My credentials are definitely correct so is it a case of my request/credentials being set incorrectly?
This is what I have (removed personal info):
var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));
var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}
A quick look over their documentation seems to indicate that the projects.json endpoint accepts the following in the body of the POST:
{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}
You're sending the User-Agent as the POST body. I'd suggest you change your code as follows:
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
This posts the payload as specified in the docs and sets your user agent in the headers as it should be.
my code is:
HitBtcApi.HitBtcApi hitbtc = new HitBtcApi.HitBtcApi();
hitbtc.Authorize("xxx", "xxx");
RestRequest request2 = new RestRequest("/api/2/account/balance", method.GET);
var x= await hitbtc.Execute(request2, true);
MessageBox.Show(x.content.ToString());
this error rising when running:
{"error":{"code":1001,"message":"Authorization required","description":""}} but when i use "/api/2/public/symbol" instead of "/api/2/account/balance" it work. please help me. thanks.
Did you activate the access right to the specific API for your API key?
https://hitbtc.com/settings/api-keys
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new
System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes(
"user:pass")));
var result = await (await client.GetAsync("https://api.hitbtc.com/api/2/trading/balance")).Content
.ReadAsStringAsync();
}
I have problem to redirect to other page, for example, while i am keeping Credential Cache. I'm using:
cCache.Add(new Uri("http://mypage.com"), "Basic", new NetworkCredential("admin", "admin"));
and with:
using (var client = new HttpClient(new HttpClientHandler { Credentials = cCache }))
{
var request = new System.Net.Http.HttpRequestMessage()
{
RequestUri = new Uri("http://mypage.com"),
Method = HttpMethod.Get,
};
var result = new HttpResponseMessage();
var requestTask = client.SendAsync(request).ContinueWith((argRequestTask) =>
{
result = argRequestTask.Result;
});
requestTask.Wait();
}
status code that i get is 200 OK, and that is good. Result that i get is content of that page and that is good to, but im still on same page. If i redirect with:
Response.Redirect("http://mypage.com");
i lose my credentials. How i can solve this? tnx