RestSharp, Basic Auth - c#

I have a question about making an authorized call to a GET Url using RestSharp.
I have a provided basic token, which looks something like this: dGVzdG5hbWU6dGVzdHBhc3N3b3Jk.
Let's say the GET Url is: https://sometest.api.com/todos?id=1 and requires authorization.
How would I pass the above token in the above GET Url?
I tried this:
var client = new RestClient("https://sometest.api.com") // base address
var request = new RestRequest("todos?id=1"); // resource
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic dGVzdG5hbWU6dGVzdHBhc3N3b3Jk");
var response = client.Execute(request);
This does not seem to work. Do I need to add the basic token as a parameter instead, or both in the header and as parameter?
Or would I need to use the client.Authenticator on the RestClient:
client.Authenticator = new HttpBasicAuthenticator("testname", "testpassword");
Any help is appreciated, thanks.
Best Regards

Could you provide more information how did you conclude that it does not work? Any exception? An error message you could provide?
How did you get that token? What the expiration time of the token?
This is how I am doing it, pretty much like you, except I am using different token type:
var request = CreateServerRequest(_configuration.SOME_URI);
request.AddHeader("Authorization", $"Bearer {Token}");
request.AddJsonBody(request);
var server = new RestClient(_configuration.SOME_ENDPOINT);
var serverResponse = server.Execute(request);
if (serverResponse.StatusCode == HttpStatusCode.OK)
{
return new ServiceResponse<bool>(true);
}
Where the method CreateServerRequest contains only:
return new RestRequest(uri)
{
RequestFormat = DataFormat.Json,
Method = Method.POST
};
Hope this helps,
Cheers and happy coding.

Related

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

Not able to add parameters to make GET request with C# RestSharp client

This is my first time working with APIs and I'd really appreciate your help and patience on bearing with me.
I'm making a GET request to the client Synccentric for getting data [Given URL below I'm using for ref].
https://api.synccentric.com/?version=latest#cb8d3255-7639-435e-9d17-c9e962c24146
[Update]
I found a way to attach parameters to querystrings and the response was validated. I'm still stuck with passing the array of fields.
var client = new RestClient("https://v3.synccentric.com/api/v3/products");
var request = new RestRequest(Method.GET);
Console.WriteLine("**** Adding Headers, Content Type & Auth Key ****");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer {{MyAPIToken}}");
request.AddParameter("campaign_id", 12618);
request.AddParameter("downloadable", 1);
request.AddParameter("downloadable_type", "csv");
string[] fields = new[] { "asin", "upc", "actor", "all_categories", "is_eligible_for_prime", "listing_url" };
request.AddParameter("fields", fields);
IRestResponse response = client.Execute(request);
I think I know where the problem is
So the [5]th parameter should ideally hold this value "[\n \"asin\",\n \"upc\",\n \"additional_image_1\",\n \"category\",\n \"is_eligible_for_prime\",\n \"listing_url\"\n ]"
But instead it looks like this.
Can you guys help me with this?
I tried the API call using Python and referencing the documents and I did get the desired response.
Attaching the python block below:
import requests
url = 'https://v3.synccentric.com/api/v3/products'
payload = "{\n \"campaign_id\": 12618,\n \"fields\": [\n \"asin\",\n \"upc\",\n \"additional_image_1\",\n \"category\",\n \"is_eligible_for_prime\",\n \"listing_url\"\n ]\n} #\"downloadable\":1,\n \"downloadable_type\":\"csv\"\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer {{MyAPIToken}}'
}
response = requests.request('GET', url, headers = headers, data = payload, timeout= 100000 , allow_redirects= 0)
print(response.text)
After the execution I got the response I was looking for.
RestSharp will not allow you to send a GET request with a content-body. The error says it all.
You will have to send the parameters as query parameters.
Console.WriteLine("**** Starting Synccentric API Fetch ****");
var client = new RestClient("https://v3.synccentric.com/api/v3/products");
var request = new RestRequest(Method.GET);
Console.WriteLine("**** Adding Headers, Content Type & Auth Key ****");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer {{MyAPIToken}}");
Console.WriteLine("**** Adding parameters ****");
request.AddParameter("campaign_id", 12618);
request.AddParameter("downloadable", "true");
request.AddParameter("downloadable_type", "CSV");
var fields = new[] { "asin", "upc", "actor", "all_categories" };
foreach (var field in fields)
{
request.AddParameter("fields", field);
}
IRestResponse response = client.Execute(request);
This will build you the following query string, which should be sent and hopefully understood okay.
https://v3.synccentric.com/api/v3/products?campaign_id=12618&downloadable=True&downloadable_type=CSV&fields=asin&fields=upc&fields=actor&fields=all_categories
UPDATE Having looked at the comments, it may be that RestSharp cannot be used with that API as it seems that it requires content body with a GET request!

oAuth uStream API

I'm trying to get data from uStream using their API and oAuth. I can get the auth token and that token does work in Rest API Client and I can get data. I however cannot get data in my project... I keep getting 401 unauth..
Code:
protected void Page_Load(object sender, EventArgs e)
{
var client = new RestClient("https://www.ustream.tv/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Basic xxxxxxxxxxxxxxxxxx");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "client_secret=xxxxxxxxxxxxx&client_id=xxxxxxxxxxxx&grant_type=client_credentials&=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
IRestResponse<TokenObject> response2 = (IRestResponse<TokenObject>)client.Execute<TokenObject>(request);
var tknName = response2.Data.access_token;
GetData(tknName);
}
public void GetData(string token)
{
var client = new RestClient("https://api.ustream.tv/channels/206844441.json");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer" + token);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse jsonResponse = client.Execute(request);
IRestResponse<Channel> json2Response2 = (IRestResponse<Channel>)client.Execute<Channel>(request);
var blah = json2Response2.Content;
}
The jsonResponse comes back 401... but I can use the token in API client like Insomnia and it will work... I can get data.
Any ideas on what I'm doing wrong?
Thanks!
Assuming token is not prefixed with a single space, then this line:
request.AddHeader("authorization", "Bearer" + token);
Should instead be (added a space after Bearer):
request.AddHeader("authorization", "Bearer " + token);
Additionally, the GET request for data does not require the Content-Type header to be added to the request; although including is unlikely to cause an error.
As João mentioned, the main problem will be the missing space character between the string "Bearer" and the token itself . After you fix this i'm pretty sure it will work.
Yes, Content-Type is superfluous for GET request, but it does not harm the success of your request.
In addition, you don't need to provide client secret twice. That's enough to provide it through the Authorization header or the client_secret property in the request body.
So, that's enough to provide the secret that way:
request.AddHeader("authorization", "Basic xxxxxxxxxxxxxxxxxx");
Ant in this case you shouldn't provide the secret again in the request body, here's the modified call, based on the original code:
request.AddParameter("application/x-www-form-urlencoded", "client_id=xxxxxxxxxxxx&grant_type=client_credentials&=", ParameterType.RequestBody);
There were actually two things I had wrong. First one pointed out by #João Angelo was the missing space between the string: Bearer & token.
Second and most frustrating was that authorization needed to be Authorization... with the capital A. Now it works... .Thanks for the help.

How to make REST GET in Asp.net C#?

I can get an access token of Office 365. I can not make a REST request (GET) attaching this token in the header.
I'm using this code:
RestClient client = new RestClient();
client.EndPoint = #"https://outlook.office365.com/api/v1.0/me/folders/inbox/messages?$top=10";
client.Method = HttpVerb.GET;
client.ContentType = "application/json";
client.PostData = "authorization: Bearer " + myAccesToken.ToString();
String json = client.MakeRequest();
I've tested the access token in http://jwt.calebb.net and it's ok.
But it's always returning:
The remote server returned an error: (400) Bad Request.
I'm kind a knewby to REST and my english is not that good... Sorry! :)
(RE)EDIT
I've tried with RestSharp and I've simplified a bit my code...
Now I'm using my access token to make the GET request.
How do I add the "authorization bearer" to my request?
Is it like this?
//Ask for the token
var client = new RestClient("https://login.windows.net/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", Request.QueryString["code"]);
request.AddParameter("redirect_uri", myRedirectUri);
request.AddParameter("client_id", myClientID);
request.AddParameter("client_secret", myClientSecret);
IRestResponse response = client.Execute(request);
string content = "[" + response.Content + "]";
DataTable dadosToken = (DataTable)JsonConvert.DeserializeObject<DataTable>(content);
//I don't need a DataTable, but it was a way to retrieve my access token... :)
//Ask for info with the access token
var client2 = new RestClient("https://outlook.office365.com/api/v1.0/me");
var request2 = new RestRequest(Method.GET);
request2.AddHeader("authorization", myToken.ToString());
//I've tried this way also:
//client2.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(dadosToken.Rows[0]["access_token"].ToString(), "Bearer");
IRestResponse response2 = client2.Execute(request2);
string content2 = "[" + response2.Content + "]";
Response.Write(content2); //this returns NOTHING!
Thanks again!
You can also use Fiddler to figure out if the Request is well formed.
Try a simpler endpoint first like: https://outlook.office365.com/api/v1.0/me
and check if the right data comes back. You can call this endpoint just from the browser and also look at the request/respond inside Fiddler.
The first thing to check: Is it a bad request. This usually means the method can't be found or the given parameters cannot be located. Check the deploy and make sure it is the most up to date version and also check that your server is actually running.

Add a GET parameter to a POST request with RestSharp

I want to make a POST request to a URL like this:
http://localhost/resource?auth_token=1234
And I want to send JSON in the body. My code looks something like this:
var client = new RestClient("http://localhost");
var request = new RestRequest("resource", Method.POST);
request.AddParameter("auth_token", "1234");
request.AddBody(json);
var response = client.Execute(request);
How can I set the auth_token parameter to be a GET parameter and make the request as POST?
The current version of RestSharp has a short method that makes use of a template:
var request = new RestRequest("resource?auth_token={token}", Method.POST);
request.AddUrlSegment("token", "1234");
Alternatively, you can add a parameter without a template:
var request = new RestRequest("resource", Method.POST);
request.AddQueryParameter("auth_token", "1234);
or
var request = new RestRequest("resource", Method.POST);
request.AddParameter("auth_token", "1234", ParameterType.QueryString);
This should work if you 1) add the token to the resource url and 2) specify ParameterType.UrlSegment like this:
var client = new RestClient("http://localhost");
var request = new RestRequest("resource?auth_token={authToken}", Method.POST);
request.AddParameter("auth_token", "1234", ParameterType.UrlSegment);
request.AddBody(json);
var response = client.Execute(request);
This is far from ideal - but the simplest way I've found... still hoping to find a better way.

Categories

Resources