I have
curl --include --request POST --header "Content-Type: application/x-www-form-urlencoded" --data-binary "username=xx#xxtemple.net&password=XXXXXXXX" 'https://api.xxsuccess.com/v1/auth'
running without ANY errors and go what I want.
When I run the following C# code on the SAME machine, I got 502 Bad Gateway Error:
string requestUri = "https://api.xxsuccess.com";
var client = new RestClient(requestUri);
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("xx#xxtemple.net", "XXXXX");
var request = new RestRequest("v1/auth", Method.POST);
IRestResponse restResponse = client.Execute(request);
Any idea how troubleshoot the problem ?
Why "Curl" is working and the code is not.
--data-binary does POST the data (in this case your username and password) in the request body. HttpBasic Authentication puts your authentication info into the Authorization header. So these are different requests.
If the first request is working, you need to put the data in the body also for the RestSharp request
var client = new RestClient(requestUri);
var request = new RestRequest("v1/auth", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("username","yourusername", ParameterType.GetOrPost);
request.AddParameter("password","yourpassword", ParameterType.GetOrPost);
Related
I need to convert that curl request to c#. Im using RestSharp. curl request:
> curl -X POST -i https://gw.api.alphabank.eu/sandbox/auth/token \
-u "{{client_id}}:{{client_secret}}" \
-d "grant_type=client_credentials&scope=account-info-setup"
I tried the following code but I end up with 'invalid_grant' error as a response.
Any ideas what i'm doing wrong?
My code:
var client = new RestClient(url);
var request = new RestRequest();
request.Method = Method.POST;
client.Authenticator = new HttpBasicAuthenticator(ABclientID, ABclientSecret);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("scope", "account-info-setup");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/x-www-form-urlencoded"; };
IRestResponse response = client.Execute(request);
this sample code is generated by Postman and it's working for my api which accepts application/x-www-form-urlencoded, can you add your parameters like this? Or create and make your request works on Postman and generate to C#-RestSharp it's usually works for me with minor changes.
var client = new RestClient("url");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("userId", "1234");
request.AddParameter("count", "5");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Turns out "invalid_grant" meant wrong credentials. I was giving wrong client-secret.
Request was succesfull after correcting the client_secret.
My curl is
curl -X POST -d "email=jeff#example.com" -d "password=*******"
--user admin#example.com:password https://example.com/admin/web/users/add
what I have so far is
var client = new RestClient("https://example/admin/web/users/add");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("application/x-www-form-urlencoded", "email=jeff#example.com" + "password=********", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
what i dont understand is where do I put
--user admin#example.com:password
Unless specified otherwise, curl uses HTTP Basic authentication when making HTTP(S) requests.
In RestSharp, HTTP Basic auth is provided via the RestSharp.Authenticators.HttpBasicAuthenticator type:
var client = new RestClient("https://example/admin/web/users/add");
client.Authenticator = new HttpBasicAuthenticator("admin#example.com", "password");
...
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);
}
I'm trying to write a C# application that will call an api for Pacer.gov. First thing I need to do it get a cookie to pass with my request. I'm using Chrome's Postman app to try to generate a POST request. Can someone explain what I'm doing wrong?
The instructions I got from Pacer.gov to get the authentication token are
For credentials, you can POST username(loginid) and password(passwd) to the authentication service here https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl
This will issue you a PacerSession cookie.
Here are some ways I tried:
(I’m just showing ##### as the login and ***** as the password, but I used the actual login and password when I tried it)
Including username and password in the URL
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-in/check-pacer-passwd.pl?loginid=#####&passwd=*****");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "a5bd0d9c-85f5-4ed6-6ad8-ac06e553f5db");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);
o Received HTML page saying “Access to PACER requires a valid account id and password. “
Including username and password in the header
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "add9dedf-10bf-eab4-428a-134c0e8a1783");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("passwd", "*****");
request.AddHeader("loginid", "#####");
IRestResponse response = client.Execute(request);
o Received HTML page saying “Access to PACER requires a valid account id and password. “
Including username and password in the body as form data
var client = new RestClient("https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "454a8ebd-b2b4-3db2-0c5c-c48e2964c671");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001");
request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"loginid\"\r\n\r\n#####\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"passwd\"\r\n\r\n*****\r\n-----011000010111000001101001--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
o Received message “Could not get any response”
Typing URL into Chrome with the username and password
https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl?loginid=#####&passwd=*****
o Received error “This site can’t be reached”
UPDATE - 5-31-16
I've made several more attempts, but am still not getting the cookie back. I tried this code:
var client = new RestClient("https://pacer.login.uscourts.gov");
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "#####");
request.AddParameter("passwd", "*****");
IRestResponse response = client.Execute(request);
When I look at the response, there is one cookie called JESSIONID which appears just to be a generic browser session ID, not the authentication code I'm expecting:
I'm not exactly sure what to expect from the response, but I know that a "NextGenCSO cookie" was mentioned in one of the e-mails from Pacer. If I login through the web browser and look at the cookies, I see a NextGenCSO cookie; I'm guessing I should be seeing something similar in the response from the API call:
UPDATE - 6-3-16
Thanks to help from #jonathon-reinhart, I was able to get the authentication cookie working with this code:
// Authentication
var client = new RestClient("https://pacer.login.uscourts.gov");
client.CookieContainer = new System.Net.CookieContainer();
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "#####");
request.AddParameter("passwd", "*****");
IRestResponse response = client.Execute(request);
var PacerSession = "";
foreach (RestResponseCookie cookie in response.Cookies)
{
if (cookie.Name == "PacerSession")
{
PacerSession = cookie.Value;
}
}
You are not correctly POSTing as the directions indicate.
Putting this:
https://pacer.login.uscourts.gov/cgi-bin/check-pacer-passwd.pl?loginid=#####&passwd=*****
into the address bar is not a POST. That's a GET with query string parameters.
See the RestSharp homepage for an example on how to POST:
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
You want to include loginid and passwd as data ("parameters" as RestSharp calls them), not has headers.
So you should be instead doing something like this:
var client = new RestClient("https://pacer.login.uscourts.gov");
var request = new RestRequest("/cgi-bin/check-pacer-passwd.pl", Method.POST);
request.AddParameter("loginid", "####");
request.AddParameter("passwd", "****");
IRestResponse response = client.Execute(request);
After a couple of days sorting out OAuth2 at the server-end (Spring java) I started working on the client written in C#. I am using RestSharp to call my web API but I am having real difficulty with the OAuth2. There is hardly any documentation and the few examples I found online do not work. Can someone provide me a code sample that is up to date and that I can use?
So far I have the following:
var client = new RestClient("http://example.com/myapi/oauth/token");
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddHeader("Content-Type", "application/json");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "client-app");
request.AddParameter("client_secret", "secret");
var response = client.Execute(request);
I am simply running this code in debug mode and when I look into the response I get unauthorized.
When I do curl on the console with the same parameters it works fine but it seems I can't make this to work in C#. Here is the curl command:
curl -H "Accept: application/json" client-app:secret#example.com/myapi/oauth/token -d grant_type=client_credentials
By the way, I have replaced my true API urls and other information with placeholders.
See RFC 6749 - 4.4.2. Client Credentials - Access Token Request
Here is the basic format of the request
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
Your cURL request
curl -H "Accept: application/json" \
-d grant_type=client_credentials \
client-app:secret#example.com/myapi/oauth/token
The reason your cURL command works
Default Content-Type (if not specified) with POST (default when you use -d switch) is application/x-www-form-urlencoded
Default authentication type, if not specified, is Basic. The username and password are passed either through the -u option or in the URL
-u username:password (client-app:secret)
-- or put it in the url --
client-app:secret#example.com/myapi/oauth/token
You could also specify the auth type with --basic or --digest
You can use the -v switch in your cURL command to see all the headers involved in the request.
RestSharp fix:
Set the Content-Type to application/x-www-form-urlencoded
Add the Basic authentication
client.Authenticator = new HttpBasicAuthenticator("client-app", "secret");
Get rid of
request.AddParameter("client_id", "client-app");
request.AddParameter("client_secret", "secret");
Set the Accept header to application/json
I am able to get both of the following functions worked.
public RestClient getClient2(string user, string token)
{
RestClient client = new RestClient();
client.BaseUrl = new Uri(baseUrl);
client.Authenticator = new HttpBasicAuthenticator(user, token);
//client.Authenticator = new OAuth2UriQueryParameterAuthenticator(token); //works
//client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(token); // doesn't work
return client;
}
public GitHubUser GetGitHubUser2()
{
RestRequest request = new RestRequest();
request.Resource = "/users/huj";
request.RootElement = "GitHubUser";
RestClient client = getClient2(myUser, myToken);
return Execute<GitHubUser>(client, request);
}
/// <summary>
/// http://stackoverflow.com/questions/30133937/how-to-use-oauth2-in-restsharp
/// </summary>
/// <returns>GitHubUser</returns>
public GitHubUser GetGitHubUser3()
{
//RestRequest request = new RestRequest(Method.POST); //empty data
RestRequest request = new RestRequest();
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("grant_type", "client_credentials");
request.Resource = "/users/huj";
request.RootElement = "GitHubUser";
RestClient client = getClient2(myUser, myToken);
return Execute<GitHubUser>(client, request);
}