oAuth uStream API - c#

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.

Related

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!

RestSharp, Basic Auth

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.

Convert Postman code to regular C# code

var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "0e4d8dba-29da-0b26-1b43-1bf974e9b5de");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
I can send request successfully and login to site in postman, but I can't do it in VS. This is my code in VS:
var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddParameter("IsPersistent", true, ParameterType.GetOrPost);
request.AddParameter("Password", "myPass", ParameterType.GetOrPost);
request.AddParameter("UserName", "myUsername", ParameterType.GetOrPost);
request.AddParameter("returnUrl", "/Account/Login", ParameterType.GetOrPost);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
but I get "unauthorized" message (401) in VS
you can use PostMan Auto C# Code generator
I believe your issue is that you're adding things that should be part of the body as parameters (based on the screenshot from PostMan showing these items as part of the body). This is untested but may work for you.
var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddBody(new
{
IsPersistant = true,
Password = "myPass",
UserName = "myUsername",
returnUrl = "/Account/Login"
});
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
You probably need to do a GET of the page first, then when making then POST reflect back all cookies received during the GET (if that RestClient of yours doesn't do that automatically).
Login pages typically add a cookie during GET and expect that cookie during POST to prevent XSRF (this involves including that same token as a form's hidden field, although the XSRF token is apparently not present in your Postman payload). It also wouldn't surprise me that some cookie-based sessionID filter is blocking you even before your request hits the login controller/middleware. In any case, doing the GET first and then reflecting the cookies in POST should work.

RestSharp - Token authentication

I'm trying to send a GET request with a token authentication, but i get an unauthorized response.
If i send the same request on Postman, it works.
Here's my code :
string url = string.Format("{0}batchs", MyUrl);
RestClient client = new RestClient(url);
RestRequest getRequest = new RestRequest(Method.GET);
getRequest.AddHeader("Accept", "application/json");
getRequest.AddHeader("Authorization", "token " + MyToken);
getRequest.AddParameter("name", MyName, ParameterType.QueryString);
IRestResponse getResponse = client.Execute(getRequest);
And here's my postman request :
Postman request
Any ideas on how to correct this ?
Thanks !
I'm not sure exactly what kind of auth you're using, but I use a firebase token generated at runtime, and this is the only thing I could get to work for me.
request.AddHeader("authorization", "Bearer " + _fireBaseService.AuthToken);

How to add json to RestSharp POST request

I have the following JSON string that is passed into my c# code as a string parameter - AddLocation(string locationJSON):
{"accountId":"57abb4d6aad4","address":{"city":"TEST","country":"TEST","postalCode":"TEST","state":"TEST","street":"TEST"},"alternateEmails":[{"email":"TEST"}],"alternatePhoneNumbers":[{"phoneNumber":"TEST"}],"alternateWebsites":[{"website":"TEST"}],"auditOnly":false,"busName":"593163b7-a465-43ea-b8fb-e5b967d9690c","email":"TEST EMAIL","primaryKeyword":"TEST","primaryPhone":"TEST","rankingKeywords":[{"keyword":"TEST","localArea":"TEST"}],"resellerLocationId":"5461caf7-f52f-4c2b-9089-2ir8hgdy62","website":"TEST"}
I'm trying to add the JSON to a RestSharp POST request like this but it's not working:
public string AddLocation(string locationJSON)
{
var client = new RestClient(_authorizationDataProvider.LocationURL);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", _authorizationResponse.Token);
...
request.AddJsonBody(locationJSON);
var response = client.Execute(request);
}
The response comes back as "Bad Request". Here is what I get if I inspect the response in the debugger:
{"code":"invalid_json","details":{"obj.address":[{"msg":["error.path.missing"],"args":[]}],"obj.rankingKeywords":[{"msg":["error.path.missing"],"args":[]}],"obj.alternatePhoneNumbers":[{"msg":["error.path.missing"],"args":[]}],"obj.busName":[{"msg":["error.path.missing"],"args":[]}],"obj.accountId":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateEmails":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateWebsites":[{"msg":["error.path.missing"],"args":[]}],"obj.email":[{"msg":["error.path.missing"],"args":[]}],"obj.primaryKeyword":[{"msg":["error.path.missing"],"args":[]}],"obj.auditOnly":[{"msg":["error.path.missing"],"args":[]}]}}
I have inspected the request parameters after calling AddJsonBody and the value appears to be including the escape sequence for double quotes - which seems to be the issue.
{\"accountId\":\"57abb4d6aad4def3d213c25d\",\"address\":{\"city\":\"TEST\",\"country\":\"TEST\",\"postalCode\":\"TEST\",\"state\":\"TEST\",\"street\":\"TEST\"},\"alternateEmails\":[{\"email\":\"TEST\"}],\"alternatePhoneNumbers\":[{\"phoneNumber\":\"TEST\"}],\"alternateWebsites\":[{\"website\":\"TEST\"}],\"auditOnly\":false,\"busName\":\"84e7ef98-7a9f-4805-ab45-e852a4b078d8\",\"email\":\"TEST EMAIL\",\"primaryKeyword\":\"TEST\",\"primaryPhone\":\"TEST\",\"rankingKeywords\":[{\"keyword\":\"TEST\",\"localArea\":\"TEST\"}],\"resellerLocationId\":\"06b528a9-22a6-4853-8148-805c9cb46941\",\"website\":\"TEST\"}
so my question is how do I add a json string to the request body?
I've ran into this problem as well. Try something like this instead of AddJsonBody.
request.AddParameter("application/json", locationJSON, ParameterType.RequestBody);
This should work:
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(yourObject), ParameterType.RequestBody);
If you directly add the serialized object, the problem is the Json convert is adding "\" before each ".
I have tried like this and it working fine, Add Bearer with token
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Bearer " + "your token key");
request.AddHeader("accept", "application/json");

Categories

Resources