Exception with OAuth2.0 service call - c#

I write some code in Microsoft Visual Studio .NET with C#. I want to call one rest service using RestSharp 106.3.1 library that i get from Microsoft NuGet.
this is a banking service that has no argument and list all customer debit card.
I get bearer access token from another service and I can call getCards service with System.Net.Http.HttpClient successfully. but I want to use RestSharp.
my code is:
var client = new RestSharp.RestClient(webSrvUri);
client.Authenticator = new RestSharp.Authenticators.OAuth2AuthorizationRequestHeaderAuthenticator(accessToken, "Bearer");
var request = new RestSharp.RestRequest(RestSharp.Method.POST);
request.RequestFormat = RestSharp.DataFormat.Json;
request.Parameters.Clear();
request.Resource = "getCards";
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
RestSharp.IRestResponse response = client.Execute(request);
but this code generate following content as result:
{"timestamp":"2018-07-03 10:16:49","status":500,"error":"Internal
Server
Error","exception":"com.fasterxml.jackson.databind.JsonMappingException","message":"No
content to map due to end-of-input\n at [Source: ; line: 1, column:
0]","path":"/core/getCards"}
what do I do?
Thanks in advance.

Related

How To Get OAuth 2.0 Access Token From Postman Using C#

Im trying to make an app that allows you to upload files to dropbox.
I created upload system etc. on this app and created postman page to get Token.
My Postman Auth2.0 Page
When i try to get access token by clicking "Get New Access Token" its works like a charm!
But i dont have any idea to get this token in c# i tried to create php post function but its return this page
my code is this i think im taking wrong url or something please help;
var client = new RestClient("https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=<clientid>&redirect_uri=https%3A%2F%2Foauth.pstmn.io%2Fv1%2Fbrowser-callback");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer <author. code>");
request.AddHeader("Content-Type", "text/plain");
request.AddHeader("Cookie", "locale=en; t=<t>; __Host-js_csrf=<auto-code>; gvc=<gvc>");
var body = #"\";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
print(response.Content);
I get this code by taking the link and clicked code and converted to c# on postman website https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=<clientid>&redirect_uri=https%3A%2F%2Foauth.pstmn.io%2Fv1%2Fbrowser-callback

Instagram Basic Display API: RestSharp Invalid authorization code response

Trying to to add an Instagram feed to my ASP.NET C# web app using this and this documentation
The issue is that I always get the Invalid authorization code error message when trying to get the short lived token via RestSharp call to https://api.instagram.com/oauth/access_token
In Postman the response is successful, is there something wrong with the RestSharp API call?
RestSharp API call
var client = new RestClient(_shortLivedTokenRequestString);
var request = new RestRequest(Method.POST);
request.AlwaysMultipartFormData = true;
request.AddParameter("client_id", _Instagram_App_Id, ParameterType.RequestBody);
request.AddParameter("client_secret", _Instagram_App_Secret, ParameterType.RequestBody);
request.AddParameter("grant_type", "authorization_code", ParameterType.RequestBody);
request.AddParameter("redirect_uri", _Instagram_App_Redirect_Uri, ParameterType.RequestBody);
request.AddParameter("code", authorizationCode, ParameterType.RequestBody);
IRestResponse<GetShortLivedTokenResponse> response = client.Execute<GetShortLivedTokenResponse>(request);
response: {"error_type": "OAuthException", "code": 400, "error_message": "Invalid authorization code"}
response object
Postman request/response
Postman response headers
I recently had a similar problem that involved not removing the #_ added at the end of the code parameter like described here.
I don't know if thats your case but maybe it helps
My problem was that I did not remove the #_ as described in the instructions:

How to get results from a Jira Rest API request?

I want to be able to take JSON data that I get from a RestRequest to the Jira Rest API and put that information into a graph. However I am unable to even write the response data to the console. I know what information I should be getting because when I make the request in postman I get a response with the expected data in it.
Here is my code that I generated directly from postman to hopefully replicate what postman is doing inside of visual studio.
How do I get the results from the Jira Rest API request that I am making?
I'm thinking it is a relatively simple fix, but I am just not that familiar with interacting with this API.
var client = new RestClient(myCompanyURL/rest/api/2/issue/NID-3.json");
var request = new RestRequest(Method.GET);
//request.AddHeader("postman-token", "tokenGeneratedFromPostman");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic myEncodedInformation");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\n\t\"fields\": {\n\t\t\"project\":\n\t\t{\n\t\t\t\"key\":\"NID\"\n\t\t},\n\t\t\"summary\": \"TEST\",\n\t\t\"description\": \"Test Description\",\n\t\t\"issuetype\": {\n\t\t\t\"name\":\"Task\"\n\t\t}\n\t}\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response);

400 Bad Request when getting access token for ExactOnline using RestSharp

I need to go through the OAuth2 flow for ExactOnline but I get stuck on step 3 of the docs (https://developers.exactonline.com/#OAuth_Tutorial.html%3FTocPath%3DAuthentication%7C_____2)
I created the following c# code using the Postman chrome app for testing http requests but keep getting 400 errors (bad request). The postman app also gave me 400 errors but no matter what settings I set, I always seem to get a 400 error.
var authToken = "veryyyyyylongtoken";
var redirectUri = "the-url-I-set-in-the-dashboard";
var grantType = "authorization_code";
var clientId = "id-guid";
var clientSecret = "secret";
var exactAccesTokenRequestEndpoint = "https://start.exactonline.nl/api/oauth2/token";
var client = new RestClient(exactAccesTokenRequestEndpoint);
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", String.Format("code={0}&redirect_uri={1}&grant_type={2}&client_id={3}&client_secret={4}", authToken, exactAccesTokenRequestEndpoint, grantType, clientId, clientSecret), ParameterType.RequestBody);
var response = client.Execute(request);
How is this code wrong?
The app registered at Exact is running in test mode, not production.
Any ideas?
===== EDIT =====
Based on Gusman's pointers I changed the code to the following. This still give a 400 error.
var client = new RestClient(exactAccesTokenRequestEndpoint);
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("code", authToken, ParameterType.RequestBody);
request.AddParameter("redirect_uri", redirectUri, ParameterType.RequestBody);
request.AddParameter("grant_type", grantType, ParameterType.RequestBody);
request.AddParameter("client_id", clientId, ParameterType.RequestBody);
request.AddParameter("client_secret", clientSecret, ParameterType.RequestBody);
var response = client.Execute(request);
Your first issue is solved by Gusman.
My guess is that the second problem is related to the exactAccesTokenRequestEndpoint you have set. Exact is really picky on the URL and I doubt if that URL you have is the URL described in the App store settings in EOL. Make sure it is at least the URL given in the settings.
So if your settings contains http://localhost/abc/, your redirect_uri should be at least http://localhost/abc/ and not http://localhost/abc, which may seem valid.
Ok, solved it. Had to UrlDecode the token I got back from the Exact response in step 2, before passing it to the request in step 3. Like so:
var authToken = WebUtility.UrlDecode("code/token");
Thanks to everybody who weighted in on the matter :-)
I can't see which REST client are you using, but I can assume the "request.AddParameter" call expects Name, Content and ParamType.
If that's the case then you added it wrong, you need to do:
request.AddParameter("code", authToken, ParameterType.RequestBody);
request.AddParameter("redirect_uri", redirectUri, ParameterType.RequestBody);
and so on, you must add one by one the request parameter and let the rest client construct the body.
EDIT: I see the client is only on the name, ok, that's what RestSharp expects :)

how to call webservicemethod in windows service

Basically my idea is to develop a proxy which will run in windows
I have created windows service application which running successfully and i have integrated a web service code in the windows service application running in windows service.
How to call that web service method when the client hits my url?
How to form the url which can call web service method to get the method return value?
OK, I'll try to answer.
Let's assume you want to call REST web service. What do you need? A HttpClient and (probably) JSON/XML Serializer. You can use built-in .NET classes, or a library like RestSharp
Sample calling REST web service using RestSharp
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", 123); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
You are not required to use RestSharp, no. For simple cases HttpWebRequest (+DataContractJsonSerializaer or Xml analogue) will be just perfect
Having SOAP web service?
Follow the instructions provided here

Categories