RestSharp posting Client Secret to Api - restsharp

I am replacing WebClient from RestSharper to call the Rest client.
Below is the working code from WebClient but the same code is not working from RestClient
WebClient:
using (var client = new WebClient())
{
var reqparm =
new System.Collections.Specialized.NameValueCollection
{
{"client_id", _configurationTickle.ClientId},
{"client_secret", _configurationTickle.ClientSecret},
{"grant_type", "authorization_code"},
{"code", authCode},
{"redirect_uri", _configurationTickle.CallBackUrl}
};
byte[] responsebytes = client.UploadValues(url, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
RestSharp:
var client1 = new RestClient(_configurationTickle.BaseUrl);
var request = new RestRequest(_configurationTickle.TokenRequestEndPoint,Method.POST);
request.AddParameter("client_id", _configurationTickle.ClientId);
request.AddParameter("client_secret", _configurationTickle.ClientSecret);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", authCode);
request.AddParameter("redirect_uri", _configurationTickle.CallBackUrl);
IRestResponse response = client1.Execute(request);
Can you please help whats wrong with the request in RestSharp, I am getting Invalid request error.
Thanks in advance.

urlencoded type request should be given as below and please check with the below modified code
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "Key1=value1&Key2=value2&....", ParameterType.RequestBody);
Modified Code:
var client1 = new RestClient(_configurationTickle.BaseUrl);
var request = new RestRequest(_configurationTickle.TokenRequestEndPoint,Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
String body="client_id="+_configurationTickle.ClientId+"&client_secret="+_configurationTickle.ClientSecret+"&grant_type=authorization_code&code="+authCode+"&redirect_uri="_configurationTickle.CallBackUrl;
request.AddParameter("application/x-www-form-urlencoded", body, ParameterType.RequestBody);

Related

Requesting a API token with both basic authentication and application/x-www-form-urlencoded

I'm trying to create an application using MS Visual Studio in either vb.net or C# to receive a token for a web api that has both basic authentication and application/x-www-form-urlencoded. When I send the request from Postman the requested works. Please see Postman screen shots below. When is use the below code I receive and message "Request failed with status code NotFound" back and the request fails. Can any point in the the right direction to resolve this.
Thank you
Postman
postman body
`private void button1_Click(object sender, EventArgs e)
{
Uri baseurl = new Uri("https://api address/token");
RestClient client = new RestClient(baseurl);
//client.Timeout = -1;
RestRequest request = new RestRequest("post", Method.Post);
request.AddHeader("Authorization", "Basic M2U4Y");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials",true);
request.AddParameter("scope", "https://?????????",true);
RestResponse response = client.Execute(request);
if (response.Content == "")
{
textBox1.Text = response.ErrorException.Message ;
}
else
{
textBox1.Text = response.Content;
}
}
`
I solved the problem. With the below code.
Uri baseurl = new Uri("https://api address/token");
RestClient client = new RestClient(baseurl);
RestRequest request = new RestRequest(baseurl, Method.Post);
request.AddHeader("Authorization", "Basic M2U4Y");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=https://FED0C291",arameterType.RequestBody);RestResponse response = client.Execute(request);
if (response.Content == "")
{
textBox1.Text = response.ErrorException.Message ;
}
else
{
textBox1.Text = response.Content;
}

The server committed a protocol violation. Section=ResponseStatusLine : Issue

I created ASP.NET core 6 API project and used JWT authentication for each API end point.
But while executing in some physical system works fine but some other physical system and server throws below error
The server committed a protocol violation. Section=ResponseStatusLine
Sample Code
var request = (HttpWebRequest)WebRequest.Create(endpoint);
var token = System.Threading.Tasks.Task.Run(async() => await new Token("URL", "username", "pwd"])).Result;
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
var postData = JsonConvert.SerializeObject(Details, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var responses = (HttpWebResponse)request.GetResponse();
Sample code based on HTTP Client
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), endpoint))
{
string token = SalesOperationAPIToken("url", "usertest", "pwd");
request.Headers.TryAddWithoutValidation("accept", "*/*");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
string json = JsonConvert.SerializeObject(Details);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = httpClient.SendAsync(request).Result;
var responseMessage = response.Content.ReadAsStringAsync().Result;
}
}
I am not sure what configuration need to be changed to get this worked in all system.
Thanks in advance.

Upload File Without Multipart/Form-Data Using RestSharp

Below, there is a POST Request Done With Standard HttpWebRequest , and HttpWebResponse. Basically it post binanry file with some parameters.
How Can I do The Same Thing With RestSharp ?
Source:
https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/SpeechCustom, ATT_APIPlatform_SampleApps/RESTFul/Speech/Csharp/app1/ ]
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty+parEndPoint );
httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken);
httpRequest.Headers.Add("X-SpeechContext", parXspeechContext);
if (!string.IsNullOrEmpty(parXArgs))
{
httpRequest.Headers.Add("X-Arg", parXArgs);
}
string contentType = this.MapContentTypeFromExtension(Path.GetExtension(parSpeechFilePath));
httpRequest.ContentLength = binaryData.Length;
httpRequest.ContentType = contentType;
httpRequest.Accept = "application/json";
httpRequest.Method = "POST";
httpRequest.KeepAlive = true;
httpRequest.SendChunked = parChunked;
postStream = httpRequest.GetRequestStream();
postStream.Write(binaryData, 0, binaryData.Length);
postStream.Close();
HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();
A simple upload example:
RestClient restClient = new RestClient("http://stackoverflow.com/");
RestRequest restRequest = new RestRequest("/images");
restRequest.RequestFormat = DataFormat.Json;
restRequest.Method = Method.POST;
restRequest.AddHeader("Authorization", "Authorization");
restRequest.AddHeader("Content-Type", "multipart/form-data");
restRequest.AddFile("content", imageFullPath);
var response = restClient.Execute(restRequest);

RESTfull Service is not accepting object as parameter

[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json)]
public string StudentUsers(Student user)
{
return string.Format("Hello {0}", user.Name);
}
Above code is my REST service. And my client code is :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
Student user =
new Stuent {
Name="Test User",
Email = "test#test.com",
Password = "test"
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(user.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, user);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
My service is hosted and I'm using webHttpBinding. When I debug my REST service I'm receiving null in Student object. I am sure that my post method is sending data as I test it by taking Name, Email and Password as parameters at REST service so my data is posted successfully but the thing is my Json data which is posted is not getting converted to Student object. I read somewhere that RESTfull Service will convert that Json data to object. Is that true or we need to convert it explicitly?
You need to sent the Content-Length for your POST-ed data:
request.ContentLength = ms.Length;
see here for more details:
I have fixed the issue by changing WebInvoke to
[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare)]

failed to Login to a remote website

I spent too much hours to overcome this, till now with no success
From my site which is developed in MVC im trying to send a login request to a remote site, for example, facebook.
From fiddler It seems that the following inputs are required charset_test, lsd, locale,email, pass.
lsd key seems to be the unique token
Here is my code
CookieContainer cookies = new CookieContainer()
private string GetToken()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string htmlText = reader.ReadToEnd();
HtmlDocument document = new HtmlDocument(); --> HtmlAgilePack object
document.LoadHtml(htmlText);
//Need to check xpath doesn't return null object
HtmlNode node = document.DocumentNode.SelectNodes("//input[#name='lsd']").First();
return node.Attributes["Value"].Value;
}
private void Login()
{
string postData = string.Format("charset_test=fixcharset_test&lsd={0} &locale=en_US&email=myemail&pass=mypass", HttpUtility.UrlEncode(GetToken()));
Uri uri = new Uri("http://www.facebook.com/login.php");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.Method = "POST";
request.AllowAutoRedirect = true;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
//After login to facebook suppose to
public string void AddFriend()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string status = response.StatusDescription;
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseDat
}
Keep in mind, that facebook is just an example, Im aware of its API, Im trying to login to site with no API.
sadly, the response return a facebook page with a sorry message for unrecognizing my browser.
Any help will be more than appreciate.
Thanks,
Are you setting HTTP_USER_AGENT on your request?