I am getting StatusCode: 401 "Unauthorized" in a HttpClient.PostAsync (C#) - c#

I am trying to use an Api Rest (IGDB) making an Http Post Request with HttpClient; this request needs to have a key and a body. I am providing the key in HttpClient.DefaultRequestHeaders.Authorization, but I am getting a 401 status code, I know that the key works because I have used it in Postman and It worked fine, so I must be implementing it wrong.
My code:
private async Task<string> ConsumeApi()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Key Name", "Key Value");
//Makes the client request only Json data
//client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("aplication/json"));
string theUri = "https://api-v3.igdb.com/games";
var stringcontent = new StringContent("fields name", UnicodeEncoding.UTF8,"application/json");
var response = await client.PostAsync("https://api-v3.igdb.com/games", stringcontent);
return response.ToString();
}
And these are Postman pictures of what I am trying to implement (works fine):

AuthenticationHeaderValue
is not setting a header but is an authorization header. Set a normal header value, not one prefixed with Authentication.

Related

Why getting 401 when trying validating Token

I have a Bearer token and need to validate it against a api and validateToken endpoint. The endpoint aspects a json like that:
{
"jwtToken": "my token"
}
At the swagger I try successful this endpoint using url
http://10.212.226.31:5022/api/v1/validateToken
But I need to validate from code and there I get a 401 'Unauthorized'.
HttpClient client = new HttpClient
{
BaseAddress = new Uri("http://10.212.226.31:5022/")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string token = accessToken.Replace("Bearer ", "");
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/v1/validateToken", token);
At the response object I get the 401.
What is wrong? Some thing about the json?
How to hand over the right stuff to the endpoint?
Additions:
I work remote on a virtual machine from a costumer and he does not allow installing software. Fiddler and co is not available.
I tried also this, but it's not working:
ValidateTokenRequest tokenJson = new ValidateTokenRequest
{
jwtToken = token
};
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/v1/validateToken", tokenJson);
I needed to authenticate my self at the endpoint, to add the token to the header.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Now it works. Thanks to everybody!

404 when accessing Design Automation API v3 through HttpClient

Running calls to the Design Automation API in Postman works just fine but when I try to make the same calls in C# using HttpClient they fail with a 404 that seems to actually hide an authentication error:
{
"developerMessage":"The requested resource does not exist.",
"userMessage":"",
"errorCode":"ERR-002",
"more info":"http://developer.api.autodesk.com/documentation/v1/errors/err-002"
}
That link leads to an authentication error:
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>1F52E60A45AEF429</RequestId>
<HostId>
[ Some base64 ]
</HostId>
</Error>
I'm following examples for how to use HttpClient, but I may be missing something. I successfully get the access token, run
var client = new HttpClient
{
BaseAddress = new Uri("https://developer.api.autodesk.com/da/us-east")
};
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(TokenType, AccessToken);
then
var result = await client.GetAsync("/v3/forgeapps/me");
and the above json is the result's content. I use the same access token in Postman and it works.
I would wrap up the endpoint, headers, and httpmethod in the HttpRequestMessage. Then send it and assign it to HttpResponseMessage.
var client = new HttpClient
{
BaseAddress = new Uri("https://developer.api.autodesk.com/da/us-east/")
};
//throw the endpoint and HttpMethod here. Could also be HttpMethod.Post/Put/Delete (for your future reference)
var request = new HttpRequestMessage(HttpMethod.Get, "v3/forgeapps/me");
//also maybe try throwing the headers in with the request instead of the client
request.Headers.Add(TokenType, AccessToken);
// send the request, assign to response
HttpResponseMessage response = await client.SendAsync(request);
//then, we can grab the data through the Content
string result = await response.Content.ReadAsStringAsync();

API Get requires Content-Type application/json;charset=UTF-8 - Issue with Http Client

I am working with an API service that requires Content-Type to be set to application/json;charset=UTF-8.
If I make a request without the charset=UTF-8 I get a 406 - Not Acceptable.
I can make a call through Postman setting the Content-Type as required, but if I use my .Net Http Client I get the error:
System.FormatException: 'The format of value
'application/json;charset=UTF-8' is invalid.'
Is there anyway I can work around this validation and force the Http Client to accept the value?
UPDATE:
Here is my latest attempt,it still throws the error.
Body.Headers.ContentType = new MediaTypeHeaderValue("application/json;charset=UTF-8");
UPDATE: Content-Type is indeed an invalid header. The API Developers removed it at our request.
Try to set the property:
new MediaTypeHeaderValue("application/json")
{
CharSet = Encoding.UTF8.WebName
};
Try this one
HttpClient httpClient= new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
Not sure if still relevant, but I recently ran into this same issue and was able to solve by setting the header in the following way:
string str = $"application/vnd.fmsstandard.com.Vehicles.v2.1+json; charset=UTF-8";
client.DefaultRequestHeaders.Add("Accept", str);
Try adding double quotes around UTF-8, like this:
Body.Headers.ContentType = new MediaTypeHeaderValue("application/json;charset=\"UTF-8\"");
EDIT:
Ok, try something like this. It's working for me locally with a WebApi I already had handy. Notice there is a header specification for what content-type will be ACCEPTED, and then there is a header for what content-type will be SENT with the request. For this example, both of them are JSON:
public static async Task<string> HttpClient(string url)
{
using(HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json")); // ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
request.Content = new StringContent("{\"id\" : 1}",
Encoding.UTF8,
"application/json"); // REQUEST header
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
I only added the authentication header to it and it worked for me. AuthToken is either a string variable or the token itself. I left out the content type header and it just works. Below is the code; Response is a string that has to be serialized to a Jobject.
{
String Response = null;
HttpClient client = new HttpClient(CertByPass());
client.Timeout = TimeSpan.FromMinutes(5);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AuthToken);
Response = await client.GetStringAsync(url);
}
Try creating a client helper class like:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(whatever your url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
return client;

Add authorization permanent token header to POST JSON using HttpClient in REST API

I am trying to POST a JSON with HhttpClient using a permanent token authorization, but I always get an error 401 Unauthorized code:
public static async Task<Uri> CrearitemAsync(Item item)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("OAuth", AuthToken);
HttpResponseMessage response = await client.PostAsJsonAsync(
"items/" + IdProvider, JsonConvert.SerializeObject(item));
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
}
I also tried this:
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthToken);
The token seems to be fine. It is an alphanumeric string all lower case. Is this the correct way to use a permanent token?
update The key i have to use for the header is: IDENTITY_KEY
but still failing
finally it worked with Add.. had to use this 'key' value rather than authorization in the header:
client.DefaultRequestHeaders.Add("IDENTITY_KEY", AuthToken);

Set request Content-Type on WinRT HttpClient

I'm developing a Windows 8.1 Store apps with C# and .NET Framework 4.5.1.
I'm trying to do a POST to a REST API but I get an Unsupported Media Type with this code:
public async Task<HttpResponseMessage> POST(string url, string jsonContent)
{
Uri resourceUri;
resourceUri = ValidateUri(url);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
HttpRequestHeaderCollection headers = httpClient.DefaultRequestHeaders;
// Try to add user agent to headers.
if (headers.UserAgent.TryParseAdd(_userAgent))
headers.UserAgent.ParseAdd(_userAgent);
// Add Content-Type and Content-Length headers
headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));
return response;
}
If I change this line:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));
With this one:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(string.Empty));
It works. I don't get 415 status code.
jsonContent value is:
{"UserName":"My Name","Provider":"Facebook","ExternalAccessToken":"Access token omitted"}
Because I haven't found any similar code on Internet, and I only have 4 views on this question; I will share the answer.
I have fixed this problem changing the post with this code:
response = await httpClient.PostAsync(resourceUri,
new HttpStringContent(jsonContent, UnicodeEncoding.Utf8, "application/json"));
You can pass "Content-Type" on HttpStringContent constructor. More info here.

Categories

Resources