restsharp get error (authentication) - authentication

I have a API GET call that works in postman BUT not in VS2017. I copied the code
from postman:
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "19763da3-4b00-4e92-83e0-1ac75f99d219");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
request.AddParameter("undefined", "{\n \"username\":\"domain\\\\username\",\n \"password\":\"myPasswd\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
The error I am getting is unauthorized, the API required a header of X-XSRF-TOKEN with a value of 71cf12361-8090-499a-adc3-2d5e98a04143 (a fake key)
Using postman, everything works just fine, but using VS2017 I get an error:
{"status":"unauthorized","error":"Login is required","errormsg":null}
What's weird (I am new to this so pardon my ignorance)is that the header does not contain:
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
but rather the parameter does, which is confusing since I thought the AddHeader would add it to the header but maybe I am misunderstanding something....
any advice/suggestions would be extremely welcomed
thank you in advance
dougc

Please use the below code and check
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
//Make sure to give the Valid Token
request.AddHeader("Authorization","X-XSRF-TOKEN <<Generated Token>>");
IRestResponse response = client.Execute(request);
Console.WriteLine("Response :" + response.Content);

Related

How to corectly set the ContentType property in HttpWebRequest (or how to fix the missing Content-Type header)

I thought I'd share something that took me some time to figure out:
I wrote a simple Post method using HttpWebRequest class.
In HttpWebRequest you can't use HttpWebRequest.Headers collection to set your desired headers when there is a dedicated property for it - you must use that dedicated property. ContentType is one of them. So I created my HttpWebRequest like this:
HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest;
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = false;
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.ContentType = "application/json";
somewhere below I set the body of my request like this:
using (StreamWriter streamWriter = new StreamWriter(streamWebRequest))
{
streamWriter.Write(sJson);
}
and posted the request using:
WebResponse webResponse = httpWebRequest.GetResponse();
But I kept getting a "400 - Bad Request" error, while the same request worked from Postman. After analyzing the request with Fiddler I found that when I send the request from my app, the Content-Type: application/json header is missing. All the other headers were present, except for Content-Type. I thought I'm setting it wrong, so I googled but didn't find a good answer. After much experimentation I found, that if I move the line:
httpWebRequest.ContentType = "application/json"
after this block:
using (StreamWriter streamWriter = new StreamWriter(streamWebRequest))
{
streamWriter.Write(sJson);
}
then the httpWebRequest.ContentType = "application/json" header finally appears in the request. So, for HttpWebRequest make sure you always set your HttpWebRequest's body/content first, before you set the ContentType property.
Hope it helps
My question above already has the answer, but to mark it as "Answered" I had to add this comment:
Make sure you always set your HttpWebRequest's body/content first, before you set the ContentType property.This way the "Content-Type" header will appear in the request.

JScript REST API: read a paginated list

In JScript I need to read a list of books from a web server that has a 2-step authentication i.e. user + password and token afterwards - once you call an IP address you get a token in response which needs to be used in a header for books (Authorization; Bearer + token). Server is supposed to respond with a paginated list of books
[{"book_Id": 1,"book_Name": "AAA","book_Year": 2021}].
Path is "GET /book", parameters are: "Page" and "Size". I've managed to call the server and get token in reponse:
var xmlhttp = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp.open("GET", "http://XX.XX.XX.XX:XXXX/authenticate?username=XXX&password=XXX", false);
xmlhttp.send();
var token = JSON.parse(xmlhttp.responseText).token
and tried to use it
var header = xmlhttp.SetRequestHeader("Authorization", "Bearer "+token)
new ActiveXObject("WScript.Shell").Popup(header.responseText)
but got empty response and got stuck. I'd very much appreciate being moved on with how to read the list.
Edit
So I've added new object and now get status 404 error Not Found. Is there some error in the coding yet?
var xmlhttp = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp.open("GET", "http://XX.XX.XX.XX:XXXX/authenticate?
username=XXX&password=XXX", false);
xmlhttp.send();
var token = JSON.parse(xmlhttp.responseText).token
var xmlhttp2 = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp2.open("GET", "http://XX.XX.XX.XX:XXXX/book?limit=1", false);
xmlhttp2.SetRequestHeader("Authorization", "Bearer "+token)
xmlhttp2.send();
new ActiveXObject("WScript.Shell").Popup(xmlhttp2.responseText)

BIM 360 Field API Issues V1: GET Request works perfectly with Postman, responds "Unauthorized" with RestSharp

Trying to implement var client = new RestClient("https://bim360field.autodesk.com/fieldapi/checklists/v1/06eede44-a707-4f0b-9529-78abea6e6bf5");
var request = new RestRequest(Method.GET); https://bim360field.autodesk.com/apidoc/index.html#fieldapi/checklists/v1/checklists_api_method_2 in my C# solution.
I've set up an example Get Request in Postman. Works perfectly with the form-data, x-www-form-urlencoded, no auth, bearer token.
Tried to copy the exact Restshap Request code from Postman to my C# app. Does not work; always responds with "Unauthorized". Tried changing cookie mngmt, and auth window/nltm mngmt. Did not help.
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "91");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Cookie", "OPTOUTMULTI_REF=b7027893-8564-4b33-8f1e-de0c175d38c6; OPTOUTMULTI_GEO=NL; utag_main=v_id:016639c85215001e1ab9f566c61201090006808800bd0$_sn:4$_ss:0$_st:1545042741235$ses_id:1545040922510%3Bexp-session$_pn:1%3Bexp-session; XSRF-TOKEN=YxM2BdzM19rML7OjKGZqcD0hAqv%2F225McEm8oB3m7No%3D; 75da74d446a8376e2cf6a286ff63573ab705f04c36540fdda21c1dbc1928d4e72cabf30a63e339690e88fc3801a93e44e6e3ddc20651f602d2c5eaaf49b21d61=f795a05c211085d994bf2e08996ff747");
request.AddHeader("Host", "bim360field.autodesk.com");
request.AddHeader("Postman-Token", "0b3c652d-462c-4aba-a661-476309792018,b4d4846c-a928-406f-837c-f16809a9bccd");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.15.2");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"ticket\"\r\n\r\n{API_TICKET}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"project_id\"\r\n\r\n049bf984-b8d1-4330-a17c-0832c6facf49\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);```
I expect that this code is also working with Restsharp. Do I miss anything?
For your cookies you will need to setup a CookieContainer on your Client.
Client = new RestClient(Request.GetEnvironment())
{
CookieContainer = new System.Net.CookieContainer()
};
You don't need the Postman Token. You will want to use the Bearer Token provided by your API to make the call and add it to your headers or parameters.
When intializing RestClient you only want to pass the base url. Then pass the rest of your api path during the RestRequest initialization. This will help for future use when wanting to hit more than one end point with the same cookies.
Here is a working example for you:
// (1) Build request
var client = new RestClient();
client.BaseUrl = new System.Uri("https://bim360field.autodesk.com/");
// Set resource or end point
var request = new RestRequest();
request.Resource = "/fieldapi/checklists/v1";
request.Method = Method.GET;
// Add parameters
request.AddParameter("ticket", "{API_TICKET}");
request.AddParameter("project_id", "049bf984-b8d1-4330-a17c-0832c6facf49");
// (2) Execute request and get response
IRestResponse response = client.Execute(request);
Hope it helps!

Microsoft Translator Text API doesn't work

I want to use Microsoft Translator API but I am unable to use it.
I created a Microsoft Azure account as specified in the documentation (http://docs.microsofttranslator.com/text-translate.html) and I created a resource.
When I call the web service to get an access toke, every time I get an exception because a time out..
This is my code (it's Apex, similar to Java) :
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Length', '3495');
req.setEndpoint('https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key=[myAPIKey]');
req.setTimeout(20000);
HttpResponse res = h.send(req);
If I remove my API key or I the content length from the header, I get an error from Microsoft.
Do you know why I get this?
Thanks
You should replace [myAPIKey] with the right key. You can get it through https://www.microsoft.com/cognitive-services
EDIT
The answer above is related to GET operations. For POST, you should include the 'Ocp-Apim-Subscription-Key' header:
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Length', '3495');
req.setHeader('Ocp-Apim-Subscription-Key', '[INSERT_HERE_YOUR_TOKEN]');
req.setEndpoint('https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
req.setTimeout(20000);
HttpResponse res = h.send(req);
It works fin now.
I edit my code and it is ok :
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(theURL);
req.setHeader('Content-Type','application/xml');
Http binding = new Http();
HttpResponse res = binding.send(req);
Thanks

Getting Unauthorized error when trying to execute the RestSharp request that retrieves data from ArangoDB

If I send the http request through Postman it works and I get the result. But the same is not working and getting Unauthorized when I execute through RestSharp.
Below is the code snippet:
var client = new RestClient(
"http://Username:Password#localhost:port/_db/databaseName/_api/simple/all");
var request = new RestRequest(Method.PUT);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json",
"{\n \"collection\":\"collectionName\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return response;
According to the restsharp wiki you cannot specify the authentication parameters via the URL:
var client = new RestClient("http://example.com");
client.Authenticator = new SimpleAuthenticator("username", "foo", "password", "bar");
var request = new RestRequest("resource", Method.GET);
client.Execute(request);
in general its a good idea in such a case to drop https, and use wireshark or ngrep to inspect whats going on on the wire:
GET /_db/_system/_api/version?details=true HTTP/1.1
Host: 127.0.0.1
Connection: Keep-Alive
User-Agent: ArangoDB
Accept-Encoding: deflate
Authrization: Basic cm9vdDo=
to inspect the actualy generated authentication headers.
var client = new RestClient("http://example.com");
client.Authenticator = new SimpleAuthenticator("admin","admin");
var request = new RestRequest(Method.GET);
client.Execute(request);
This works for me..