How to add a header in HTTP request c#? - c#

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

Related

Get Access token form OneLogin using the PKCE .net core API

I'm Trying to get the access token form OneLogin using the Authorization Code with PKCE. I'm able to go through step1 for PKCe and getting the authorization code back from OneLogin. But when i try to get the token using the authorization code sent by one login i keep getting 400 bad request error. I'm not sure what is wrong. I followed the info provided by oneLogin website to all required parameters in the request for Step 2. below the code i'm using. I will appreciate if some one can help on this.
public async Task GetAccessToken(string redirecturl, string authCode)
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
var client = new HttpClient(clientHandler);
var body = JsonConvert.SerializeObject(new
{
grant_type = "authorization_code",
code = authCode, ---The code returned from OneLogin in step 1
client_id=XXXXXXXXXXXXXXXXXX386d707215718",
redirect_uri=redirecturl,--The redirect URL registered in onelogin account
code_verifier=GetCacheEntry(CodeKey)-- the code verifier used in step one
});
var req = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://MySubdomain.onelogin.com/oidc/2/token"),
Content = new StringContent(body)
};
req.Content.Headers.ContentType= new MediaTypeHeaderValue(#"application/x-www-form-urlencoded");
var response = await client.SendAsync(req);
if (response.StatusCode == HttpStatusCode.OK)
{
var responseBody =await response.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<OAuthTokenResponse>(responseBody);
memoryCache.Remove(CodeKey);
return Ok(json);
}
return BadRequest(response);
}
Looks like you're sending the body as a json content, although you've correctly specified the Content Type as x-www-form-urlencoded.
Here's how I create the body and send the request
var data = new Dictionary<string, string>(){
{ "code", code },
{ "code_verifier", AuthCodeParticipantDetail.CodeVerifier},
{ "grant_type", "authorization_code" },
{ "redirect_uri", AuthCodeParticipantDetail.CallBackUrl},
{"client_id", AuthCodeParticipantDetail.ClientId}
};
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = await _httpClient.PostAsync(url, new FormUrlEncodedContent(data));
var tokens = await response.Content.ReadFromJsonAsync<Tokens>();

How to add bearertoken to post/get restsharp automation testing

maybe anyone could help me with RestSharp api automation testing.
I'll try to be as clear as possible.
Basically the scheme is:
I'm sending my username/password credentials & I get BearerToken in return.
I parse the bearer token into a json file.
After I get the bearer token I need to "Authenticate" in order to get the information that I need.
For example i need full company credit report which I get after I input companyName ="Whatever"; companyCode = "Whatever";
{
var client = new RestClient("https://www.myapitesting.com/api/Auth/Authenticate");
var request = new RestRequest(Method.GET);
var body = new AuthenticatePostCredentials { Username = "myUserName", Password = "myPassword" };
request.AddJsonBody(body);
var response = client.Post(request);
HttpStatusCode statusCode = response.StatusCode;
int numericStatusCode = (int)statusCode;
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<object>(request).Data;
string jsonToken = JsonConvert.SerializeObject(queryResult);
var JSON1 = JToken.Parse(jsonToken);
var pureToken = JSON1.Value<string>("token");
File.WriteAllText(#"C:\Users\....\TestAPI\TestAPI\token.json", pureToken);
Console.WriteLine(pureToken);
Console.WriteLine(numericStatusCode)
The output I get is: token, status code 200 (correct credentials to get the bearertoken)
//////////At this point I get the token and it is writed into my json file/////////////// (the token works)
Now im trying to authenticate with my token and get the company information that I need
var client = new RestClient("https://www.myapitesting.com/api/GetCompanyReport");
var myRequest = new RestRequest(Method.POST);
myRequest.AddHeader("Accept", "application/json");
myRequest.AddHeader("Authorization", $"Bearer{pureToken}");
myRequest.AddHeader("content-type", "application/json");
var companyInfoInput = new AuthenticatePostCredentials { companyName = "MyCompanyName", companyCode = "MyCompanyCode" };
requestas.AddJsonBody(companyInfoInput);
var response = myRequest.Execute(request);
Console.WriteLine(response.Content);
The output I get is error code that says I havent authenticated, even though I pass the bearer token with my addHeader command.
{"ErrorId":401,"ErrorName":"Unauthorized","ErrorDescription":"User is not logged in"}
What am I doing wrong? Any kind of help would be greatly appreciated!
In this case, you could load the "Authenticator" you want to use, in the case of JWT you may instantiate something like this:
var authenticator = new JwtAuthenticator(pureToken);
and then set your client authenticator like this:
client.Authenticator = authenticator;
Mainly, you should not need to set headers by hand for the most commons ones using Restsharp.
You can for example fix this statement:
var myRequest = new RestRequest(url, DataFormat.Json);
var response = client.Post(request);
I also made this gist for you to check an example
If you want to see something more complete I also have this another gist

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!

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