I'm trying to write a specific curl request in C#, and I keep getting a 500 server error response from the server. This curl request essentially makes a post request to an API by the company Highwinds. This request sends json data, and sets the Auth Bearer token header.
This is the curl request that works fine (note that I've replaced my actual bearer token with {token} and my actual account id with {accountId} to obfuscate that info):
curl -H "Authorization: Bearer {token}" -H "Content-Type: application/json" -d "#data.json" "https://striketracker.highwinds.com/api/accounts/{accountId}/purge"
Here's the C# code that gives me a generic 500 server error from the Highwinds API (note that I've replaced my actual bearer token with {token}, my actual account id with {accountId}, and the url in the json string with {url}, in order to obfuscate that personal info):
var accountId = "{accountId}";
var purgeURI = string.Format("https://striketracker.highwinds.com/api/accounts/{0}/purge", {accountId});
var query =
#"{""list"": [{""url"": ""{url}"",""recursive"": true}]}";
var token = {token};
using (var httpClient = new HttpClient())
{
var url = new Uri(purgeURI);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
httpRequestMessage.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(),
string.Format("Bearer {0}", token));
httpRequestMessage.Content = new StringContent(query,
Encoding.UTF8,
"application/json");
await httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
{
var response = task.Result;
var blah = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
});
}
}
Thanks!
*Update: The following line of code was added to remove the Expect header that HttpRequest adds to a request by default. After removing this header I was able to get Highwinds API to accept the request without bombing.
"request.ServicePoint.Expect100Continue = false;"
My best recommendation would be to proxy both requests through something like tcpmon http://archive.apache.org/dist/ws/tcpmon/1.0/ (Basically run the server and point to local host and have tcpmon redirect the request to striketracker.highwinds.com). Try it from curl and from your source and you should be able to see what's different between the requests.
Related
I have this API where I receive an image to save it in a storage server. I've been testing the functionality in postman and works perfectly fine. But when it comes to the mobile app it does not send the image.
here you can see the Postman POST request
the code for the xamarin app is the next
var content = new MultipartFormDataContent();
var stream = File.OpenRead(_mediaFile.Path);
var streamcontent = new StreamContent(stream);
content.Add(streamcontent, "picture");
var client = new HttpClient();
HttpResponseMessage response = await cliente.PostAsync($"http://localhost:200/api/.../picture", content);
string result = response.Content.ReadAsStringAsync().Result;
Response responseData = JsonConvert.DeserializeObject<Response>(result);
if (response.IsSuccessStatusCode)
{
await Application.Current.MainPage.DisplayAlert("Correcto", "Imagen subida Correctamentel!", "OK");
_mediaFile = null;
terminado.IsEnabled = true;
}
else
{
terminado.IsEnabled = true;
await Application.Current.MainPage.DisplayAlert("Error", "Opps algo ocuirrio mal!", "OK"); }
As you can see in the postman the key picture receives the image name. I tried it also with curl and it works:
curl -X POST "http://localhost:200/api/.../picture" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "picture=#version1.jpeg;type=image/jpeg"
I've managed it to work, but using RestSharp library instead of HttpClient:
var client = new RestClient("192.168.0.2"); //the ip of your REST API
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "multipart/form-data"); // I'm using multipart form data
request.AddHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLC"); // using JWT for auth
request.AddFile("pictureField", "/path/to/file"); //the path depends on which device you're using
IRestResponse response = client.Execute(request);
Pretty much straigt forward and works perfectly fine. Also, the "pictureField" depends on the name of the field the API requires, and the path to file should not be hardcoded. It should be given depending on where in the device the choosen image is.
I have
curl --include --request POST --header "Content-Type: application/x-www-form-urlencoded" --data-binary "username=xx#xxtemple.net&password=XXXXXXXX" 'https://api.xxsuccess.com/v1/auth'
running without ANY errors and go what I want.
When I run the following C# code on the SAME machine, I got 502 Bad Gateway Error:
string requestUri = "https://api.xxsuccess.com";
var client = new RestClient(requestUri);
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("xx#xxtemple.net", "XXXXX");
var request = new RestRequest("v1/auth", Method.POST);
IRestResponse restResponse = client.Execute(request);
Any idea how troubleshoot the problem ?
Why "Curl" is working and the code is not.
--data-binary does POST the data (in this case your username and password) in the request body. HttpBasic Authentication puts your authentication info into the Authorization header. So these are different requests.
If the first request is working, you need to put the data in the body also for the RestSharp request
var client = new RestClient(requestUri);
var request = new RestRequest("v1/auth", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("username","yourusername", ParameterType.GetOrPost);
request.AddParameter("password","yourpassword", ParameterType.GetOrPost);
Im trying to do this curl request (from API documentation) in HttpClient:
Please not that the code below is just copied from their documentation and does not contain any of my information.
POST /oauth/token (get access token)
$ curl -v -X POST https://api.tink.com/api/v1/oauth/token \
-d 'code=1a513b99126ade1e7718135019fd119a' \
-d 'client_id=YOUR_CLIENT_ID' \
-d 'client_secret=YOUR_CLIENT_SECRET' \
-d 'grant_type=authorization_code'
{
"access_token": "78b0525677c7414e8b202c48be57f3da",
"token_type": "bearer",
"expires_in": 7200,
"refresh_token": "33f10ce3cb1941b8a274af53da03f361",
"scope": "accounts:read,statistics:read,transactions:read,user:read"
}
I've tried to make a post request to the oauth/token endpoint both with all the information requested as header (with an empty body) and as a json document (with and without the headers).
When I only have the information in the headers I get a 401 back, but I've verified that all the data is correct. All other ways that I've tried has generated a 400.
As far as I can understand the json below the curl is the response, but Im not accustomed at all to curl.
There's a handy site here: https://curl.olsh.me/
I wouldn't recommend sending secrets over the web, so be sure to anonymise the values first and translate them back after.
So for the command you've pasted you'd get:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.tink.com/api/v1/oauth/token"))
{
var contentList = new List<string>();
contentList.Add("code=1a513b99126ade1e7718135019fd119a");
contentList.Add("client_id=YOUR_CLIENT_ID");
contentList.Add("client_secret=YOUR_CLIENT_SECRET");
contentList.Add("grant_type=authorization_code");
request.Content = new StringContent(string.Join("&", contentList));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
}
}
The 401 headers you are getting back may be due to passing in the wrong id and secret, I presume there is a way for you to get test credentials.
I am trying to send a HTTP post request to microsoft Bing speech API o transcribe an audio file. First we need to send a post request to get an "access token" as a response, then this token is used (as authorisation" in another post request to upload the actual file and get the transcription in the response. I can send the first post request and successfully get the access token, but I am not able to get a reasonable response for my second post request. I follow this page: https://www.microsoft.com/cognitive-services/en-us/speech-api/documentation/api-reference-rest/bingvoicerecognition
This is the second post request:
Guid requestId = Guid.NewGuid();
var Uri = #"https://speech.platform.bing.com/recognize?version=3.0&requestid=" + requestId.ToString() + #"&appID=D4D52672-91D7-4C74-8AD8-42B1D981415A&format=json&locale=en-US&device.os=Windows%20OS&scenarios=ulm&instanceid=f1efbd27-25fd-4212-9332-77cd63176112";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Uri);
request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
request.Headers.TryAddWithoutValidation("Content-Type", #"audio/wav; samplerate=16000");
MemoryStream ms = new MemoryStream();
using (var fs = System.IO.File.OpenRead("audio.wav"))
{
byte[] buffer = new byte[1024 * 8];
while (fs.Read(buffer, 0, buffer.Length) > 0)
{
ms.Write(buffer, 0, buffer.Length);
}
fs.Close();
}
ms.Seek(0, SeekOrigin.Begin);
HttpContent _Body = new StreamContent(ms);
request.Content = _Body;
var client2 = new HttpClient();
var response2 = client2.SendAsync(request);
I guess the problem is where I set the "Content-Type" for the header. The reason is when I debug, I don't see this property being set in the Header of the request. In fact, there is no Content-Type in the header. Any help would be appreciated. This page, which talks about the equivalent curl command, can also be helpful: https://social.msdn.microsoft.com/Forums/en-US/ad73e4f1-e576-4080-9fe7-060cc2f583ca/microsoft-bing-voice-recognition-api-authorization-404resource-not-found?forum=SpeechService
Content-Type is a content related header. The following code works for me:
public async Task<string> SendRequestAsync(string url, string bearerToken, string contentType, string fileName)
{
var content = new StreamContent(File.OpenRead(fileName));
content.Headers.TryAddWithoutValidation("Content-Type", contentType);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
var response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsStringAsync();
}
}
The invocation in your case (if you work in synchronous context):
var result = SendRequestAsync(Uri, accessToken, "audio/wav; samplerate=16000", "audio.wav").Result;
You can send the following header instead, to not have to do 2 requests because of the token.
If you want to not have to login each time instead of using the 'Authorization': 'Bearer {TOKEN}' header you could use the 'Ocp-Apim-Subscription-Key': '{YOUR AZURE TOKEN}' in order to not have to make a authorisation factory or more requests than necessary to the application and make it faster
NOTE: {TOKEN} is a JWT token like
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzY29wZSI6Imh0dHBzOi8vc3BlZWNoLnBsYXRmb3JtLmJpbmcuY29tIiwic3Vic2NyaXB0aW9uLWlkIjoiZmFhZTNlYTkxNmI1NGMxZWEyODY4MDlhYTg3ZWE1MmUiLCJwcm9kdWN0LWlkIjoiQmluZy5TcGVlY2guUHJldmlldyIsImNvZ25pdGl2ZS1zZXJ2aWNlcy1lbmRwb2ludCI6Imh0dHBzOi8vYXBpLmNvZ25pdGl2ZS5taWNyb3NvZnQuY29tL2ludGVybmFsL3YxLjAvIiwiYXp1cmUtcmVzb3VyY2UtaWQiOiIiLCJpc3MiOiJ1cm46bXMuY29nbml0aXZlc2VydmljZXMiLCJhdWQiOiJ1cm46bXMuc3BlZWNoIiwiZXhwIjoxNTAwODgxNjIzfQ.KdlCrIJ_H0jxs1yyeyYxYR7ucbLuFKT__ep7lGJmGbU
NOTE2: {YOUR AZURE TOKEN} is like d5kals90935b40809dc6k38533c21e85 and you find it here
The request would look like this:
curl -v -X POST "https://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?language=es-ES&locale=es-ES&format=simple&requestid=req_id" -H "Ocp-Apim-Subscription-Key: d5kals90935b40809dc6k38533c21e85" -H 'Transfer-Encoding: chunked' -H 'Content-type: audio/wav; codec="audio/pcm"; samplerate=8000' --data-binary #"{BINAYFILE}.wav"
After a couple of days sorting out OAuth2 at the server-end (Spring java) I started working on the client written in C#. I am using RestSharp to call my web API but I am having real difficulty with the OAuth2. There is hardly any documentation and the few examples I found online do not work. Can someone provide me a code sample that is up to date and that I can use?
So far I have the following:
var client = new RestClient("http://example.com/myapi/oauth/token");
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddHeader("Content-Type", "application/json");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "client-app");
request.AddParameter("client_secret", "secret");
var response = client.Execute(request);
I am simply running this code in debug mode and when I look into the response I get unauthorized.
When I do curl on the console with the same parameters it works fine but it seems I can't make this to work in C#. Here is the curl command:
curl -H "Accept: application/json" client-app:secret#example.com/myapi/oauth/token -d grant_type=client_credentials
By the way, I have replaced my true API urls and other information with placeholders.
See RFC 6749 - 4.4.2. Client Credentials - Access Token Request
Here is the basic format of the request
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
Your cURL request
curl -H "Accept: application/json" \
-d grant_type=client_credentials \
client-app:secret#example.com/myapi/oauth/token
The reason your cURL command works
Default Content-Type (if not specified) with POST (default when you use -d switch) is application/x-www-form-urlencoded
Default authentication type, if not specified, is Basic. The username and password are passed either through the -u option or in the URL
-u username:password (client-app:secret)
-- or put it in the url --
client-app:secret#example.com/myapi/oauth/token
You could also specify the auth type with --basic or --digest
You can use the -v switch in your cURL command to see all the headers involved in the request.
RestSharp fix:
Set the Content-Type to application/x-www-form-urlencoded
Add the Basic authentication
client.Authenticator = new HttpBasicAuthenticator("client-app", "secret");
Get rid of
request.AddParameter("client_id", "client-app");
request.AddParameter("client_secret", "secret");
Set the Accept header to application/json
I am able to get both of the following functions worked.
public RestClient getClient2(string user, string token)
{
RestClient client = new RestClient();
client.BaseUrl = new Uri(baseUrl);
client.Authenticator = new HttpBasicAuthenticator(user, token);
//client.Authenticator = new OAuth2UriQueryParameterAuthenticator(token); //works
//client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(token); // doesn't work
return client;
}
public GitHubUser GetGitHubUser2()
{
RestRequest request = new RestRequest();
request.Resource = "/users/huj";
request.RootElement = "GitHubUser";
RestClient client = getClient2(myUser, myToken);
return Execute<GitHubUser>(client, request);
}
/// <summary>
/// http://stackoverflow.com/questions/30133937/how-to-use-oauth2-in-restsharp
/// </summary>
/// <returns>GitHubUser</returns>
public GitHubUser GetGitHubUser3()
{
//RestRequest request = new RestRequest(Method.POST); //empty data
RestRequest request = new RestRequest();
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("grant_type", "client_credentials");
request.Resource = "/users/huj";
request.RootElement = "GitHubUser";
RestClient client = getClient2(myUser, myToken);
return Execute<GitHubUser>(client, request);
}