RestSharp authentication with Api Id and Api Key - c#

I have to call a restful API, but the only details I have are an API ID and an API key.
I am trying to use Restsharp library code like this.
var client = new RestClient("https://xxxxxxx");
client.Authenticator = new HttpBasicAuthenticator("xxxxx", "yyyyyy");
I get a 401 authorization required error.
Could you please point me in the right direction.
Thanks.

Here is the solution that i came up with.
this returns the client object
private RestClient InitializeAndGetClient()
{
var cookieJar = new CookieContainer();
var client = new RestClient("https://xxxxxxx")
{
Authenticator = new HttpBasicAuthenticator("xxIDxx", "xxKeyxx"),
CookieContainer = cookieJar
};
return client;
}
and you can use the method like
var client = InitializeAndGetClient();
var request = new RestRequest("report/transaction", Method.GET);
request.AddParameter("option", "value");
//Run once to get cookie.
var response = client.Execute(request);
//Run second time to get actual data
response = client.Execute(request);
Hope this helps you.
Prakash.

I know this is old but this is partial to what I needed:
var cookieJar = new CookieContainer();
var client = new RestClient("https://xxxxxxx")
{
Authenticator = new HttpBasicAuthenticator("[username]", "[password]"),
CookieContainer = cookieJar
};
Then right after I made the request object I had to add the API_KEY header:
var request = new RestRequest("[api]/[method]"); // this will be unique to what you are connecting to
request.AddHeader("API_KEY", "[THIS IS THE API KEY]");

Related

How do i get the response from a post request? Restsharp

I have tried looking for the answer but i cant find it if you can please help
var options = new RestClientOptions("https://httpbin.org/#/HTTP_Methods/post_post")
{
ThrowOnAnyError = true,
Timeout = 1000
};
var client = new RestClient(options);
var request = new RestRequest()
.AddQueryParameter("foo", "bar");
Im using RestSharp 107.3.0 please help if you can
Use .Result which will give response from both Get and Post method in RestSharp 107.
RestClient client = new("http://baseURL");
RestRequest restRequest = new("api/test");
restRequest.AddQueryParameter("foo", "bar");
RestResponse response = client.ExecuteAsync(restRequest, Method.Post).Result;
Assert.AreEqual(HttpStatusCode.OK, response);

C# Oracle Rest API, Authentication Issue

I am trying to use Ocacle's Financial REST API and I'm having trouble making it work in C# in VS2019.
I can confirm the restful call works using Postman, so I know my credentials are fine but I must be missing something trying this with in code.
So URL is like so:
http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail
So I stick that in postman, put in my credentials (basic auth) and it works find. In VS I've tried both the RestSharp way and basic HTTPRequest way as follows:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
r.Method = "GET";
string auth = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("Username" + ":" + "Password"));
r.Headers.Add("Authorization", "Basic" + " " + auth);
r.ContentType = "application/vnd.oracle.adf.resourcecollection+json";
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
{
int b = 0;
}
RestSharp:
var client = new RestClient("http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("UserName", "Password");
//Tried authorization this way as well.
//JObject AuthRequest = new JObject();
//AuthRequest.Add("Username", "UserName");
//AuthRequest.Add("Password", "Password");
var request = new RestRequest();
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
//request.AddParameter("text/json", AuthRequest.ToString(), ParameterType.RequestBody);
request.AddHeader("Content-Type", "application/vnd.oracle.adf.resourcecollection+json");
request.AddHeader("REST-Framework-Version", "1");
var response = client.Get(request);
No matter what I try I am always 401 not authorized. I suspect its some kind of header thing? I can't see the raw request header in postman
I am new to REST. I am used to using WSDLs soap services.
Try this.
var handler = new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password")
};
using (var client = new HttpClient(handler))
{
var result = await client.GetAsync("url");
}
Good luck!
I figured out what the problem was.
In postman, it was fine with the URL I posted being HTTP but in C# code it was not. I switched the URL to HTTPS and it started working just fine.

how to use restsharp web rest api

hi there i am new to rest api
i build these api
https://dastanito.ir/test/ex2/api/storiesmaster/read.php
https://dastanito.ir/test/ex2/api/storiesmaster/read_one.php?id=60
i used requests lib in python and everything is ok
but i do not know how to use this with restsharp
var client = new RestClient("https://dastanito.ir/test/ex2/api/storiesmaster/read.php");
var request = new RestRequest("");
var response = client.Post(request);
MessageBox.Show(response.Content.ToString());
Based on RestSharp sample:
var client = new RestClient("https://dastanito.ir");
var request = new RestRequest("test/ex2/api/storiesmaster/read.php", Method.GET);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
Output:
{"StoriesMasters":[{"id":"2","story_code":"002a","master_code":"he3385_1"},{"id":"60","story_code":"001a","master_code":"he3385_1"},{"id":"3","story_code":"c57675","master_code":"ara3433_2"},{"id":"50","story_code":"d8885","master_code":"za76787_3"}]}

HttpClient calling API doesnt not pass cookie auth

Trying to call an API from a controller using HttpClient and the API does not recognize the user as authenticated and logged in. When calling the API from JS I have no issue. I noticed the HttpClient was only sending via HTTP 1.1 and so I upgraded to 2.0 settings the DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER flag but this made no difference. I have tried all combinations of the HttpClientHandler properties including UseCookies and the request is never authenticated.
using (var handler = new HttpClientHandler {UseDefaultCredentials = true})
{
using (var httpClient = new HttpClient(handler))
{
var response = httpClient.GetStringAsync(new Uri($"https://localhost:64366/api/")).Result;
}
}
Will move to token based auth in the future but for now would like to understand why there is a difference between calling the API from C# vs JS. This is all HTTPS on localhost using asp net core 2.2.
Difference between JS and C# is that browsers attach cookies automatically to requests and you have to attach cookies manually in C# as juunas mentioned.
To obtain and use authentication cookie you may use the following pattern
CookieContainer cookies = new CookieContainer(); //this container saves cookies from responses and send them in requests
var handler = new HttpClientHandler
{
CookieContainer = cookies
};
var client = new HttpClient(handler);
string authUrl = ""; //your auth url
string anyUrl = ""; //any url that requires you to be authenticated
var authContent = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("login", "log_in"),
new KeyValuePair<string, string>("password", "pass_word")
}
);
//cookies will be set on this request
HttpResponseMessage auth = await client.PostAsync(authUrl, authContent);
auth.EnsureSuccessStatusCode(); //retrieving result is not required but you will know if something goes wrong on authentication
//and here retrieved cookies will be used
string result = await client.GetStringAsync(anyUrl);

C# HttpClient not displaying all cookies

Edit: I apologize for the confusion: I'm attempting to scrape a site that I did not write; I'm not writing an ASP app. I'm only attempting to scrape one.
After making a post request to a login page, I attempt to read the cookies from another page. I do not see all the cookies I expect, however. My code is as follows:
// Downloads login cookies for subsequent requests
public async Task<CookieContainer> loginCookies()
{
var cookies = new CookieContainer();
var handler = new HttpClientHandler {
UseCookies = true,
AllowAutoRedirect = true,
CookieContainer = cookies
};
var client = new HttpClient(handler);
var loginUri = new Uri("https://connect.example.edu/login.aspx");
var credentials = new Dictionary<string, string> {
{"example$txtUsername", this.Username},
{"example$txtPassword", this.Password}
};
var formCredentials = new FormUrlEncodedContent(credentials);
await client.PostAsync(loginUri, content: formCredentials);
var pointsUri = new Uri("https://info.example.edu/");
Console.WriteLine("COOKIES:");
foreach (Cookie cookie in cookies.GetCookies(pointsUri))
Console.WriteLine($"{cookie.Name} --> {cookie.Value}");
return cookies;
}
I believe the error is a result of loginUri and pointsUri having different subdomains. The info I need to scrape exists at the pointsUri page, but the login exists at loginUri.
A cookie that I'm missing in particular is ASP.NET_SessionID.

Categories