RestCall with Restsharp not authenticated, it is with Postman - c#

I'm trying to get info from a REST endpoint that requires basic authentication.
Using postman I'm fine, getting the information I need from the call:
GET endpoint/api/workitems?ids=20449& api-version=2.0 HTTP/1.1
Host: xxx.xxx.xxx.50:8080
Authorization: Basic ABC==,Basic ZZZ cache-control: no-cache
Postman-Token: e6476d89-ec2b-439d-8821-88ef446a03a9
When I do the same with restsharp, I get an Unauthorized error:
var client = new RestClient("http://xxx.xxx.xxx.50:8080/endpoint/api/workitems?ids=20449& api-version=2.0");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "06ea7553-d35e-4743-a516-201d6e3b9084");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", "Basic ABC==,Basic ZZZ");
IRestResponse response = client.Execute(request);
Am I missing something?
Thanks

Eventually I found that the proper way to do the Basic Authentication with restsharp is the following.
It works:
var client = new RestClient("http://xxx.xxx.xxx.50:8080/endpoint/api/workitems?ids=20449& api-version=2.0");
client.Authenticator = new HttpBasicAuthenticator(username, decodedToken);
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "06ea7553-d35e-4743-a516-201d6e3b9084");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);

Related

Token Autorization in RestSharp does not appear

Good morning, I'm retrieving an authorization token using RestSharp, but instead of returning a Token, it returns an html page:
var client = new RestClient("https://iam.efatura.cv/auth/realms/taxpayers/ protocol/openid- connect/auth"); var request = new RestRequest(Method.POST); request.AddHeader("grant_type", "authorization_code"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("accept", "application/json"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=adadasdasdasdasda& scope=openid&clientSecretasdadsdadasdasdasdasdasdasdasasd& redirect_uri=https://iam.efatura.cv/auth/realms/taxpayers", ParameterType.RequestBody); IRestResponse response = client.Execute(request); Token=response.Content;

C# Restsharp GET Method Request will show "No JSON object could be decoded"

I am using C# winform on Visual Studio 2019 and using RestSharp.
I have tested WEBAPI function on POSTMAN with correct output.
So i try to implement on C# Winform.
I dump POSTMAN code (C# Restsharp) as following:
var client = new RestClient("http://192.168.2.10:88/en/product/ajax_api_getProductInfoBatch");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "21");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Host", "192.168.2.10:88");
request.AddHeader("Postman-Token", "f1ff99c7-dc02-40cb-b87a-
a046cf106a96,e2b7d88d-cfc9-4c99-8117-ec48398e56ed");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
request.AddParameter("undefined", "{\n \"Item No\":\"3101\"\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
and i revised
request.AddParameter("undefined", "{\n \"Item No\":\"3101\"\n}"
to
request.AddParameter("application/json", "{\"Item No\":\"3101\"}", ParameterType.RequestBody);
Therefore, the full code will be
private void Button1_Click(object sender, EventArgs e)
{
var client = new RestClient("http://192.168.2.10:88/en/product/ajax_api_getProductInfoBatch");
var request = new RestRequest(Method.GET);
//request.AddHeader("cache-control", "no-cache");
//request.AddHeader("Connection", "keep-alive");
//request.AddHeader("Content-Length", "22");
//request.AddHeader("Accept-Encoding", "gzip, deflate");
//request.AddHeader("Host", "192.168.2.10:88");
//request.AddHeader("Postman-Token", "86e877f8-5755-4e57-960a-eaa78b1e8b6c,da863548-65e0-4053-9cb3-b5760da94165");
//request.AddHeader("Cache-Control", "no-cache");
//request.AddHeader("Accept", "*/*");
//request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
//request.AddHeader("Content-Type", "text/plain");
request.AddParameter("application/json", "{\"Item No\":\"3101\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var content = response.Content;
textBox1.Text = content;
}
but it is still output "No JSON object could be decoded" after GET request.
Anyone share your experience will be appreciated.
or there are other ways to do GET/POST on C#.
thanks.!
You can use httpclient and pass parameters as stringcontent and type should be application/json for stringcontent.
This is for post request

Getting StatusCode: UnsupportedMediaType when using RestClient with bearer token

Getting StatusCode: UnsupportedMediaType for file upload. I am using RestClient with bearer token
I got the bearer token successfully, but when sending the JSON to the API I'm getting the exception unsupported media type
var client = new RestClient(requestAPIURL);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", string.Format("Bearer " +
token.AccessToken));
request.AddParameter("application/json",
JsonConvert.SerializeObject(jsonData), ParameterType.RequestBody);
var response = client.Execute(request);
POST the JSON in the request body:
request.AddBody(JsonConvert.SerializeObject(jsonData));

Retaining authorization header in RestSharp during redirects

I am using RestSharp to make a GET api call. The api call is authenticated through HTTP Basic authentication by passing the authorization header.
The server redirects the api call with a status code 307. My client code does handle the redirects but the authorization header is not passed to this redirected api call. This is done for valid reasons as mentioned here. Hence I do get an unauthorized error.
How can I configure the RestClient to restore the authorization header?
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I added a check that resends the api request of receiving a 401 with the below code.
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
//Resend the request if we get 401
int numericStatusCode = (int)response.StatusCode;
if(numericStatusCode == 401) {
var redirectedClient = new RestClient(response.ResponseUri.ToString());
IRestResponse newResponse = redirectedClient.Execute(request);
Console.WriteLine(newResponse.ResponseStatus);
}

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.

Categories

Resources