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?
Related
I need to send a request and to authenticate i need to add a header. I'm new to all this and probably its a stupid question but please i really need this. I tried to use HttpHeaders header = new HttpHeaders(); but theres an error.
var httpClient = new HttpClient();
HttpHeaders headers = new HttpHeaders(); // <- error
var request = httpClient.GetAsync("link").Result;
Console.ReadKey();
The error is Cannot create an instance of the abstract class or interface
I give you an example. I make a request to get access token and then add Authorization to the header.
To request the access token:
var tokenClient = new User()
{
username= "admin",
password= "#dmin",
};
HttpResponseMessage response = await client.PostAsJsonAsync<string>("https://api.example.com/api/v1/token", tokenClient);
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
Then to add Authorization to the header, add the following code:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);
I'm writing a windows service in C# that needs to authenticate with an API and make some calls. I'm able to authenticate successfully with this API I'm talking to, but I can't seem to figure out how to use the response. The response looks like this:
{"access_token":"Es-Zjs_LI0tcXyLe3aEfgKPNLHN7CwyUhTss-cTld1A","expires_in":1800,"token_type":"Bearer","scope":"example","auth_state":1,"company":"examplecompany"}
I can get the access token out of that string if I want, but no matter how I pass it to a request, I get a 401 error. This is what my current iteration looks like:
string results = "";
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",token);
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://example.ca/endpoint"),
//Headers =
//{
// { "authorization", "Bearer"},
//},
};
try
{
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
results = body;
}
}
catch (Exception ex)
{
results = "ERROR: " + ex.Message;
}
return results;
Where "token" is the string "Es-Zjs_LI0tcXyLe3aEfgKPNLHN7CwyUhTss-cTld1A" in this example. I had previously tried stitching the access_token value as a string to the "Bearer" string in the commented out section in the middle there. What am I doing wrong? Do I need to make a JwtSecurityToken out of the response?
AuthenticationResult authResult = await daemonClient.AcquireTokenForClient(new[] { MSGraphScope })
.ExecuteAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
I've used the authResult.AccessToken. Not sure if it works in your scenario. The return type in my case was Microsoft.Identity.Client.AuthenticationResult type when I retrieved the token for a Graph API that I was using.
Be aware that the token you have received ("Es-Zjs_LI0tcXyLe3aEfgKPNLHN7CwyUhTss-cTld1A") is a reference token and not a JWT-token. Make sure your API accepts that type of token.
To use the token effectively in production then I would consider using the various helper methods found in the IdentityModel library and especially the Worker application helpers.
While I understand it's largely situational depending on what API you're trying to connect to, for me the solution was to use this method to pass in the authentication token:
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + 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!
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);
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);