How to use OAuth2 in RestSharp - c#

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);
}

Related

'invalid_grant' error on API call with RestSharp

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.

How to troubleshoot 502 Bad Gateway error

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);

C# RestAPI Call

I am trying too make a rest call with C# for the first time.
I think im very close but i get an error message : Error: 400 - Bad Request.
Here is my Code:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.test123.com/oauth2/token"))
{
string webstring = String.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&client_id=${2}&client_secret={3}", access_code_string, RedirectURI,ClientId, ClientSecret);
Console.WriteLine(webstring);
request.Content = new StringContent(webstring);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
Console.WriteLine("Access token: " + response);
}
}
Here is an sample code from Curl
curl -X POST \
--header "Content-Type: application/x-www-form-urlencoded" \
--data "grant_type=authorization_code&code=dlZE0KFxhM&redirect_uri=http%3A%2F%2Fclient%2eexample%2Ecom&client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET"
"https://api.test123.com/oauth2/token"
This is the description:
Obtain an access token
After you have received the authorization code you can request an access token.
Method
POST
URL
https://api.test123.com/oauth2/token
Request format
application/x-www-form-urlencoded
Request parameters
Name Type Description
grant_type String Value must be set to authorization_code
code String The authorization code
client_id String
client_secret String
redirect_uri String The URL where the response is sent. Must match the registered redirect URI.
Response format
application/json
I took an different approach
public void call()
{
string access_code_string = Read_Json_Values("accsess_code");
string webstring = String.Format("https://api.test123.com/oauth2/token?grant_type=authorization_code&code={0}&client_id=${1}&client_secret={2}&redirect_uri={3}", access_code_string, ClientId, ClientSecret, RedirectURI);
var client = new RestClient(webstring);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", "Bearer xxxx");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.WriteLine(response.Content);
}

How to convert curl "--user" command to Restsharp?

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");
...

Curl request written in C# doesn't work

I'm trying to write a specific curl request in C#, and I keep getting a 500 server error response from the server. This curl request essentially makes a post request to an API by the company Highwinds. This request sends json data, and sets the Auth Bearer token header.
This is the curl request that works fine (note that I've replaced my actual bearer token with {token} and my actual account id with {accountId} to obfuscate that info):
curl -H "Authorization: Bearer {token}" -H "Content-Type: application/json" -d "#data.json" "https://striketracker.highwinds.com/api/accounts/{accountId}/purge"
Here's the C# code that gives me a generic 500 server error from the Highwinds API (note that I've replaced my actual bearer token with {token}, my actual account id with {accountId}, and the url in the json string with {url}, in order to obfuscate that personal info):
var accountId = "{accountId}";
var purgeURI = string.Format("https://striketracker.highwinds.com/api/accounts/{0}/purge", {accountId});
var query =
#"{""list"": [{""url"": ""{url}"",""recursive"": true}]}";
var token = {token};
using (var httpClient = new HttpClient())
{
var url = new Uri(purgeURI);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
httpRequestMessage.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(),
string.Format("Bearer {0}", token));
httpRequestMessage.Content = new StringContent(query,
Encoding.UTF8,
"application/json");
await httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
{
var response = task.Result;
var blah = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
});
}
}
Thanks!
*Update: The following line of code was added to remove the Expect header that HttpRequest adds to a request by default. After removing this header I was able to get Highwinds API to accept the request without bombing.
"request.ServicePoint.Expect100Continue = false;"
My best recommendation would be to proxy both requests through something like tcpmon http://archive.apache.org/dist/ws/tcpmon/1.0/ (Basically run the server and point to local host and have tcpmon redirect the request to striketracker.highwinds.com). Try it from curl and from your source and you should be able to see what's different between the requests.

Categories

Resources