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");
...
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.
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);
There is an external webservice that I need to post some data to create a device. They use swagger and in the swagger I can test and it works but when I use restsharp it does not work correctly. It does not give me any error (returns 200 as status code), but it does not create a device.
PS: a GET method of Wwebservice is working but the Post is not
here is the curl when I use swagger
curl -X POST "website/keys/generate" -H "accept: application/json" -H "Authorization: Bearer blablablablablabla"
-H "Content-Type: application/json" -d "{\"deviceIds\":[\"10000000\"],\"keyNames\":[\"DeviceKey1\"],
\"externalReference\":\"ERD-1\"}"
as json, the request should be
{
"deviceIds": [
"10000000"
],
"keyNames": [
"DeviceKey1"
],
"externalReference": "ERD-1"
}
and here is my code
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddParameter("deviceIds", deviceGenerationRequest.deviceIds.ToArray());
request.AddParameter("keyNames", deviceGenerationRequest.keyNames.ToArray());
request.AddParameter("externalReference", deviceGenerationRequest.externalReference);
var result = await _apiCaller.CallAPI(url, request);
and here is the CallAPI method's content
var client = new RestClient(url);
client.AddDefaultHeader("Authorization", "Bearer " + _token);
IRestResponse response;
response = await client.ExecuteGetAsync(request);
What is my mistake?
Edit:
instead of Restsharp, I've used HttpWebResponse and it works
var query = JsonConvert.SerializeObject(deviceGenerationRequest);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer blabla");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(query);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result3 = streamReader.ReadToEnd();
}
There are two ways to post data using rest sharp
Case 1
Pass all the parameters as a json in single paramter and use content type to application\json
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\r\n \"deviceIds\": [\r\n \"10000000\"\r\n ],\r\n \"keyNames\": [\r\n \"DeviceKey1\"\r\n ],\r\n \"externalReference\": \"ERD-1\"\r\n}", ParameterType.RequestBody);
Case 2
Pass parameters individually. If you are individually sending parameters then change content type to this
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("deviceIds", deviceGenerationRequest.deviceIds.ToArray());
request.AddParameter("keyNames", deviceGenerationRequest.keyNames.ToArray());
request.AddParameter("externalReference", deviceGenerationRequest.externalReference);
I am not sure about the resolution but this is most likely be the case.Apart from this everything looks good
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);
}