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.
Related
I am trying to Post a simple Json object using RestSharp to add a new product. I'm getting an error response from the server
"{"status":400,"error":"There was a problem in the JSON you submitted: unexpected character (after ) at line 1, column 2 [parse.c:724] in '{'product':{'name':'Product name','opt1':'Colour'}}"}"
My code:
////
var json = "{\'product\':{\'name\':\'Product name\',\'opt1\':\'Colour\'}}";
IRestClient restClient = new RestClient();
IRestRequest request = new RestRequest()
{
Resource = "https://api.targetsite.com/products/"
};
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/xml");
request.AddHeader("authorization", "Bearer " + token);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(json);
IRestResponse response = restClient.Post(request);
////
I managed to achive the result I wanted using a curl statment but I would like to do it using RestSharp.
Curl statment -
curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer <ACCESS_TOKEN>"
https://api.targetsite.com/products/ -d '{"product":{"name":"Product name","opt1":"Colour"}}'
This HttpClient call also works fine
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.targetsite.com/products/"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer <ACCESS_TOKEN>");
request.Content = new StringContent("{\"product\":{\"name\":\"Product name\",\"opt1\":\"Colour\"}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
}
}
It looks like a limitation on the API you are calling.
When you send the json with curl, you're using different delimiters (" instead of ').
My guess is that the API you're calling doesn't properly deserialize the JSON when ' is used.
What you can try is replacing the escaped ' with " or replace this line in your code : request.AddJsonBody(json)
with
request.AddJsonBody(Newtonsoft.Json.JsonConvert.DeserializeObject(json)) provided that you have installed the newtonsoft package.
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);
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 want to use RestSharp to issue Api calls to Gerrit but I'm having trouble with authentication.
For example there is the curl command which works:
curl --digest --user VladDracul:5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA http://localhost:8080/a/groups/
but how can I give the --user to a restSharp call?
myAuth = new HttpBasicAuthenticator("VladDracul","5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA");
restClient = new RestClient(BaseUrl);
restClient.Authenticator = myAuth;
var request = new RestRequest(Method.GET);
request.Resource = "/a/groups/";
request.AddHeader("Content-type", "application/json");
var response = restClient.Execute(request);
The response I get is "Unauthorized"
I found the answer. Adding the line gets it working.
var request = new RestRequest(Method.GET);
request.Credentials = new NetworkCredential("VladDracul", "5SAbg1pFWyqsvcs4aB7aGL2lISh8fuOjcoQK9WRGSA");;
request.Resource = "/a/groups/";
request.AddHeader("Content-type", "application/json");
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);
}