Why getting 401 when trying validating Token - c#

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!

Related

I am getting StatusCode: 401 "Unauthorized" in a HttpClient.PostAsync (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.

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();

Cannot set authorization header in c#

I'm trying to setting my Jwt token in C# code.
[HttpPost]
public IActionResult TestPOST ()
{
var token = "myExampleJwtTokenNormallyIGrabItFromOtherFunction";
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
return Ok();
}
This method just return Ok(), but Authorization is not setting. And I still have 401 http error.
I cannot figured out what can be wrong here.
I read that should I use
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
but it still does not work. How should I set header? Have anyone any idea?

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);

403 error when trying to get data from Reddit API

I am using oAuth to authenticate my app. I managed to get a code, access_token and refresh_token. So the next step would be trying to get info about the current user.
public async void GetCurrentUser()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);
var response = await client.GetAsync("https://oauth.reddit.com/api/v1/me");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
}
}
}
This is the method I am using to do that. However the response is always an 403 (Forbidden) error code. Any idea what could be wrong? The access_token is what I got when I made a request to https://oauth.reddit.com/api/v1/access_token
I think the token is correct because when I create the same request with Fiddler it works.
ANSWER:
Fixed it by adding a custom user-agent
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, _endpointUri + "me");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
request.Headers.Add("User-Agent", Uri.EscapeDataString("android:com.arnvanhoutte.redder:v1.2.3 (by /u/nerdiator)"));
var response = await client.SendAsync(request);

Categories

Resources