Validation of HTTPClient and HTTPRequest Code - c#

I am trying to send a request to Identity verification company. They are asking to send three headers. I added the headers like so:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.test");
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
client.DefaultRequestHeaders.TryAddWithoutValidation("hmac-signature", Hmackey);
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.Content = new StringContent(JSONFile, Encoding.UTF8,
"application/json");
HttpResponseMessage response = client.SendAsync(request).Result;
string responseContent = await response.Content.ReadAsStringAsync();
I posted the same JSON file in SOAP UI and I got the response back, but when I send the same JSON file using my code above, I get below error:
{
"responseHeader": {
"tenantID": "V2321",
"requestType": "PreciseIdOnly",
"clientReferenceId": "PIDInitial-2312313",
"expRequestId": "",
"messageTime": "2020-06-09T17:17:49Z",
"responseCode": "R0302",
"responseType": "ERROR",
"responseMessage": "The HMAC validation failed : Invalid Signature or no matching alias found."
},
"originalRequestData": null
}
The only difference is that in my code, I have "/r/n" and "/". I can remove "/r/n", but cannot remove "/" because double codes are preceded by forward slash.
Instead of calculating HMAC key, I got the HMAC key from SOAP UI from HTTP logs and put that in my code . I still get the same error saying "HMAC validation failed". I just want to make sure that does my code above looks right? I am supposed to add three headers like so:
Accept:application/json
Content-Type:application/json
hmac-signature:<TheCalculatedHMACSignature>
Does my code look right with these three headers. This is my first application where I am sending a request and I am thinking may be something in my code that is causing this error. I am not calculating HMAC key anymore. I am getting that key from SOAP UI Http logs and my response from SOAP UI looks good.
Any help in validating my code will be highly appreciated.

Related

Bitkub Custom Headers in PostRequest C#

I am making a Post HttpRequest, but although I added Headers to the request message the response I am getting has a field RequestMessage which doesn't contain the Headers I added.
request.Headers.Add("Accept", "application/json");
request.Headers.Add("X-BTK-APIKEY", _apiKey._public_key);
I am using PostAsync and HttpRequestMessage.Headers.Add to add custom headers to the secure endpoints of Bitkub, but I am getting {"error": 2} (Missing X-BTK-APIKEY) as return. I've tried:
Changing PostAsync to SendAsync
Changing request.Headers.Add("X-BTK-APIKEY", _apiKey._public_key) to request.Headers.Authorization = AuthenticationHeaderValue("X-BTK-APIKEY", _apiKey._public_key).
But the results are similar.

Replicate POSTMAN GET request in C#/VB.net with Authorization

I've been here for 2 days now driving me nuts.
All I want to do it call a webservice at:
https://use-land-property-data.service.gov.uk/api/v1/datasets
Which returns some JSON object.
It requires the "Authorization" header to be set with an API Key that I have.
I've tried it in POSTMAN and it works.
However trying to get a Webclient or Httpclient version working is currently beyond me. I've tried countless examples here on SO. None return the same responses as POSTMAN. All return "Request Rejected"
e.g.
Using client = New HttpClient()
client.DefaultRequestHeaders.Add("Authorization", "MYKEY")
Dim response = Await client.GetStringAsync("https://use-land-property-data.service.gov.uk/api/v1/datasets")
Return response
End Using
what is the equivalent in httpclient to replicate the postman Authorization header?
Try:
httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", "Your Key")

404 error when trying to upload crash to hockeyapp

I'm trying to upload crash manually to HockeyApp using public API. When calling the api link using Postman and uploading crash.log file it works fine but when I try to do the same from C# code I get 404 error.
Here is my code:
string log = ""; //log content
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*"));
var content = new MultipartFormDataContent();
var stringContent = new StringContent(log);
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain");
content.Add(stringContent, "log", "crash.log");
var response = await this.client.PostAsync("https://rink.hockeyapp.net/api/2/apps/[APP_ID]/crashes/upload", content);
}
I was using WireShark to analyse the request that Postman is sending and tried to make mine look exactly the same. The only difference I see is that request from C# code has filename* field in Content-Disposition for the attachment while the one from Postman doesn't:
Content-Disposition: form-data; name="log"; filename="crash.log"; filename*=utf-8''%22crash.log%22
It might be worth mentioning that the code is written in portable library in Xamarin project.
Following #Lukas Spieß sugestion I asked the question on HockeyApp support. Apparently they don't handle quotes in the boundary header. The one thing I missed comparing Postman request and mine.
Here is the solution:
var contentTypeString = content.Headers.ContentType.ToString().Replace("\"", "");
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", contentTypeString);

C# Windows Store App HTTPClient with Basic Authentication leads to 401 "Unauthorized"

I am trying to send a HTTP GET request to a service secured with BASIC authentication and https. If I use the RESTClient Firefox plugin to do so there is no problem. I am defining the basic-header and sending the GET to the url and I am getting the answer (data in json).
Now I am working on a Windows Store App in C# which is meant to consume the service. I enabled all required capabilities in the manifest and wrote the following method:
private async void HttpRequest()
{
string basic = "Basic ...........";
Uri testuri = new Uri(#"https://...Servlet");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", basic);
Task<HttpResponseMessage> response = client.GetAsync(testuri);
var text = await response;
var message = text.RequestMessage;
}
I tried out many different possibilites like getting the response-string but everything lead to an 401 Status Code answer from the Server.
I looked at many similar problems and my understanding of the communication is the following: Client request -> Server response with 401 -> Client sends Authorization header -> Server response with 200 (OK)
What I don't understand is why I am getting the 401 "Unauthorized" Status Code although I am sending the Authorization header right at the beginning. It would be interesting if someone knows how this is handled in the RESTClient.
The BASIC header is definetly correct I was comparing it with the one in the RESTClient.
It would be great if someone could help me with this.
Thanks in advance and kind regards,
Max
Was having a similar problem, i added a HttpClientHandler to HttpClient.
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("","")
var httpClient = new HttpClient(httpClientHandler);
Credentials should be encoded, before adding to the header. I tested it in WPF app, It works...
string _auth = string.Format("{0}:{1}", "username", "password");
string _enc = Convert.ToBase64String(Encoding.UTF8.GetBytes(_auth));
string _basic = string.Format("{0} {1}", "Basic", _enc);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization",_basic);

Why I cannot set 'Allow' in HTTP response header?

I've written a RESTful API using ASP.NET Web Api. Now I'm trying to make it returns the allowed verbs for a controller. I'm trying to do it with the following code:
[AcceptVerbs("OPTIONS")]
public HttpResponseMessage Options()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Methods", "POST");
response.Headers.Add("Allow", "POST");
return response;
}
But instead of getting a Allow Header on my response, I'm getting a 500 Internal Server Error. While debugging I receive the following error:
{"Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."}
Is that possible to set that header?
As the error message says, you must use content headers with HttpContent objects.
response.Content.Headers.Add("Allow", "POST");
Must admit this is kinda weird API...
Allow is a content header.
response.Content.Headers.Allow.Add("POST");

Categories