Bad Resquest in RestSharp, but working on Postman - c#

Basically, I've been trying to authenticate through oauth2 on c# using restsharp, but I am receiving a bad request response, I'm not sure if it's something related to the API configuration or if it's something I'm missing In my code.
public string getToken(string email, string password)
{
var restclient = new RestClient(loginUrl);
RestRequest request = new RestRequest("request/oauth") { Method = Method.GET };
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("email", HttpUtility.UrlPathEncode(email));
request.AddParameter("password", HttpUtility.UrlPathEncode(password));
request.AddParameter("grant_type", HttpUtility.UrlPathEncode("password"));
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
string token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}
this is the response when I execute that code
An this is the postman execution
Thanks!

I think there problem with adding parameters the way you are adding.
latest restsharp support this,
Also,avoid encoding of params by setting to false
var request = new RestRequest("resource", Method.GET);
request.AddQueryParameter("email", "test#test.com",false);

var restclient = new RestClient(loginUrl); I think you need to check your url.

Try this.. you OAuth is password grantype are your sure your not missing any credentials like client_id, scope and client_secret.
public static string getAccessToken(string usern, string pswd)
{
RestClient client = new RestClient(ConfigurationManager.AppSettings["TokenUrl"]);
RestRequest request = new RestRequest() { Method = Method.GET};
request.AddParameter("grant_type", "password", ParameterType.GetOrPost);
request.AddParameter("username", usern, ParameterType.GetOrPost);
request.AddParameter("password", pswd, ParameterType.GetOrPost);
IRestResponse response = client.Execute(request);
var responseJson = response.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
return token;
}

Related

How to capture Json from web site using c#

I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True
I'd like to collect JSON response using C#
Below is my horrible code
string cookie = "my super secret cookie string";
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent","Mozilla/5.0");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";
request.AddParameter("cookie", cookie, ParameterType.Cookie);
var client = new RestClient(url);
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
How can I get it to return JSON to me? I am getting something but not the JSON I want
Try updating your Access header to application/json.
request.AddHeader("Accept", "application/json");
Accept indicates what kind of response from the server the client can accept.
You can get more info for Accept from Header parameters: “Accept” and “Content-type” in a REST context
After poking around for a bit I figured it out. For the benefit of all:
private bool FinancialStatement(string symbol, string statement, string period)
{
var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";
var client = new RestClient(target);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", MACHINE_COOKIE);
IRestResponse response = client.Execute(request);
dynamic responseObj;
try
{
responseObj = JsonConvert.DeserializeObject(response.Content);
}
catch (Exception)
{
return false;
}
return response.IsSuccessful;
}

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

Spotify API - Getting 406 Unacceptable On Token Request When Using HttpRequestMessage

In my requests to Spotify's "get token" endpoint using .NET's HttpRequestMessage, I'm getting a 406 (Unacceptable) response.
Here's my post method (fyi, this is not optimized code -- more of a proof of concept):
public static async Task<string> PostForm(HttpClient httpClient, string url, List<KeyValuePair<string, string>> nameValueList)
{
using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, url))
{
httpRequest.Content = new FormUrlEncodedContent(nameValueList);
using (var response = await httpClient.SendAsync(httpRequest))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
I'm calling that method with this:
public Token GetSpotifyToken()
{
var httpClient= new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
httpClient.DefaultRequestHeaders.Add("Authorization", "Basic MyApiCredsBase64EncodedYesIveConfirmedTheseWork=");
var url = "https://accounts.spotify.com/api/token";
var grantType = new KeyValuePair<string, string>("grant_type", "client_credentials");
return JsonConvert.DeserializeObject<Token>
(ApiRequest.PostForm(postClient, url,
new List<KeyValuePair<string, string>>() { grantType } )
.GetAwaiter()
.GetResult());
}
I know that the issue is related to how grant_type=client_credentials is getting added to the request. This method, which uses RestSharp, works fine:
public Token GetSpotifyToken()
{
var client = new RestClient("https://accounts.spotify.com/api/token");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", "Basic MyApiCredentialsBase64Encoded=");
request.AddParameter("undefined", "grant_type=client_credentials", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return JsonConvert.DeserializeObject<Token>(response.Content);
}
But I've tried adding grant_type=client_credentials to the HttpRequestMessage object in a few different ways, without success.
Figured it out, right after I posted this.
In the above code, the line...
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
...was causing the problem. Omitting it allowed the code to work.

Cookie missing in Restsharp response

I use Restsharp for a WPF client that I'm developing.
It appears that I receive no cookies in the client.CookieContainer where it has always 0 items after I successfully authenticate to our server.
It's weird because the same request is sent with Postman and I receive a JSESSIONID cookie that is not present when the request is sent with Restsharp.
public static async Task<IRestResponse> SendLogonRequest(string UID, SecureString pwd)
{
var restClient = new RestClient(new Uri(URLSRV))
{
Authenticator = new HttpBasicAuthenticator(UID, pwd.ToInsecureString()) //base64 auth;
};
restClient.CookieContainer = new CookieContainer();
var restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("Accept", "application/json");
restRequest.AddHeader("Content-Type", "application/json");
var cancellationTokenSource = new CancellationTokenSource();
var restResponse = await restClient.ExecuteTaskAsync(restRequest, cancellationTokenSource.Token);
return restResponse;
}
I've seen on a post that if the cookie has a HttpOnly flag it will not work. (see: https://stackoverflow.com/a/21072840/7031019)
this doesn't help me because I can't change anything from server side.
Thank you

How do I programmatically login with IdentityServer4 using code

So here's my code that I'm trying.
Uri uri = new Uri(_environmentConfiguration.AuthorityLoginRequestUrl);
string content = $#"Username={ userID }&Password={ userPassword }";
var request = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
_httpClient.SetBearerToken(token.AccessToken);
var response = await _httpClient.PostRequest(uri, request);
The response I get back is a status 400: Bad Request.
Obviously there is something wrong with the request. Either headers/cookies and/or query.
Any ideas?

Categories

Resources