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

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

Related

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.

OkHttp Post Body as JSON is throwing 404

I recently moved into OKHTTP. I'm able to perform get request but while performing post i'm getting 404. Can someone help me out where I'm going wrong.
FYI:
auth token is correct & url is valid
public void PullRequest() throws IOException{
JSONObject jo = new JSONObject();
jo.put("head","patch-7");
jo.put("base","main");
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jo.toString());
//RequestBody body = RequestBody.create(jo.toString(),JSON);
Request request = new Request.Builder()
.url(url)
.header("Authorization",authorization)
.post(body)
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
if (response.code()>300) {
System.out.println("error...");
System.out.println(response.body().string());
}else {
System.out.println(response.body().string());
}
}

API test using RestSharp keeps returning 'Unauthorized Access, invalid API key'

I've been trying to figure this out for a couple of days now and that includes looking at similar posted questions but I can't seem to get it to work.
I am trying to post a request to retrieve a Token which I can then use for further API GET requests.
The request I am posting is the below:
[TestMethod]
public void GetToken()
{
var client = new RestClient(baseUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("Authorization", bearer, ParameterType.HttpHeader);
request.AddParameter("username", username);
request.AddParameter("password", password);
request.AddParameter("api_key", apiKey);
IRestResponse restResponse = client.Execute(request);
Console.WriteLine("Status code: " + (int)restResponse.StatusCode);
Console.WriteLine("Status message " + restResponse.Content);
}
When I run the request, I get the following:
Status code: 200
Status message {"content":null,"error":"Unauthorized Access, invalid API key","success":false}
I cannot figure out why I keep getting the invalid API Key value. In terms of all the variables I use, when I post the request in Postman, it works perfectly fine.
Ok, so I had a look at the code with a developer and turned out I needed to be passing in my apikey as part of the AddParameter value.
So my final code looked like:
[TestMethod]
public void GetToken()
{
var client = new RestClient(baseUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("Authorization", "Bearer " + apiKey, ParameterType.HttpHeader);
request.AddParameter("username", username);
request.AddParameter("password", password);
IRestResponse restResponse = client.Execute(request);
Console.WriteLine("Status code: " + (int)restResponse.StatusCode);
Console.WriteLine("Status message: " + restResponse.Content);
}

RestSharp posting Client Secret to Api

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

Twitter streaming API - Error 401 Unauthorized

Running a java main program to call twitter streaming api. I have generated a bearer token and passing to the api. But getting the error response Error 401 Unauthorized
Is passing the bearer token right way to authenticate? If not what is the right way to do this?
SSLConnectionSocketFactory sslsf = getSSLConnectionFactory();
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpHost target = new HttpHost("stream.twitter.com", 443, "https");
new BasicHttpContext();
HttpPost httpPost = new HttpPost("/1.1/statuses/filter.json");
StringEntity postEntity = new StringEntity("track=birthday","UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
//httpPost.setHeader("Authorization", "Bearer " + Base64.encodeBase64(bearerToken.getBytes()));
httpPost.setHeader("Authorization", "Bearer " + bearerToken);
httpPost.setHeader("User-Agent", "Your Program Name");
httpPost.setHeader("Host", "stream.twitter.com");
HttpResponse response = httpClient.execute(target, httpPost,new BasicHttpContext());
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
if(buffer.length()>30000) break;
}
System.out.println(buffer);
//return new EventImpl(buffer.toString().getBytes());
} catch (Exception e) {
e.printStackTrace();
}