retweet with oauth c# - c#

I have tried to use twitter api to retweet a status , and use below code to send a post request
webRequest = WebRequest.Create("https://api.twitter.com/1.1/statuses/retweet/241259202004267009.json") as HttpWebRequest;
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Headers.Add("Authorization: OAuth oauth_consumer_key=\"xxxxx\", oauth_nonce=\"xxx\", oauth_signature=\"xxxx\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1352642106\", oauth_token=\"xxxx\", oauth_version=\"1.0\"");
requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(string.Empty);
requestWriter.Close();
The user is authenticated with my twitter application in previous step but the above code do simply nothing and even do not returning any error.

You need to call webRequest.GetResponse() to actually send the request.

Related

Jenkins ERROR 403 No valid crumb was included in the request - using github authentication

Recently I upgraded from a very old jenkins version from 2016 to 2.289.1. I updated all the plugins as well. Previously we had it setup with github security. When we would send jobs, it would be sent with the username and oauth key generated from github, and that's how we would track who sent jobs.
After upgrading, every time I would try to send a job I would get HTTP ERROR 403 No valid crumb was included in the request. I've tried a lot of different solutions I found online, like checking Enable proxy compatibility under crsf protection, or downloading the crumb plugin. I even started requesting the crumb and attaching it to the header. In all cases I was still getting the crumb error.
Now if I disabled the github authentication and changed it to jenkins own user database, and replaced the username and token with a jenkins one (and kept the code to insert the crumb into the header) then the job would successfully get sent to jenkins. I would rather do it through github since that is how we have it setup, anyone have any suggestions now how to get around the crumb error?
here is just a piece of the code that sends the request
HttpWebRequest crumbRequest = WebRequest.Create(jenkinsCrumbUrl) as HttpWebRequest;
crumbRequest.Method = "GET";
HttpWebResponse crumbResponse = (HttpWebResponse)crumbRequest.GetResponse();
StreamReader responseReader = new StreamReader(crumbResponse.GetResponseStream());
string responseString = responseReader.ReadToEnd();
var crumb = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString);
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
request.Method = "POST";
request.ContentType = contentType;
request.UserAgent = userName;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
request.PreAuthenticate = true;
byte[] credentialBuffer = new UTF8Encoding().GetBytes(String.Format("{0}:{1}", userName, APIToken));
request.Headers["Authorization"] = String.Format("Basic {0}", Convert.ToBase64String(credentialBuffer));
request.Headers[crumb["crumbRequestField"]] = crumb["crumb"];
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
return request.GetResponse() as HttpWebResponse;

HTTPWebRequest returns 401 unauthorized

I make a POST HTTPWebRequest to an URL to download a file. The problem is request fails with message authentication failed. But the same request made via POSTMAN app works fine. Error I receive is :
The remote server returned an error: (401) Unauthorized. Protocol Error.
The fiddler capture of requests between the two shows that POSTMAN has few additional ciphers, ec_point_formats, elliptic_curves, signature_algs. Not sure if that matters but in the interest of keeping this post short I am not giving the actual differences but can provided if asked for.
Sample code I use:
// create a request
HttpWebRequest request; = (HttpWebRequest)WebRequest.Create(inputUri);
SetProxy(inputProxyUri, inputProxyUser, inputProxyPassword, request);
request.ProtocolVersion = HttpVersion.Version11;
//Set authorization
string authorisation = string.Format("{0}:{1}", user, pass);
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authorisation));
string header = string.Format("{0} {1}", "Basic", encoded);
request.Headers[HttpRequestHeader.Authorization] = header;
request.KeepAlive = false;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(requestParams);
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
//Get response stream
System.IO.Stream responseStream = ((HttpWebResponse)request.GetResponse()).GetResponseStream();
I have played with request object mentioned below :
request.ProtocolVersion = HttpVersion.Version11;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.Accept = "*/*";
Also changed registry to enable TLS 1.2, enable TLS-1.2 for client and server SCHANNEL communications as mentioned in https://www.derekseaman.com/2010/06/enable-tls-12-aes-256-and-sha-256-in.html without much luck.
Any help would be appreciated.

rest api is not giving desired results

I am not getting the results that documentation says. I login the Buddy; created application; copy this URL and assign to url string; when I execute the program I am not getting results that are expected (status + Accesstoken) as documentation says. Can anyone please tell me if I am missing something as newbie to http calls. Its running on http requester but not on Poster firefox add-on!
Documentation
http://dev.buddyplatform.com/Home/Docs/Getting%20Started%20-%20REST/HTTP?
Code
string parameters = "{appid:'xxxxxx', appkey: 'xxxxxxx', platform: 'REST Client'}";
private async void SimpleRequest()
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse) await request.GetResponseAsync();
}
catch (Exception)
{ }
}
Using the HTTP requester add-on on Firefox, I successfully retrieved an access token so their API work.
In C# they provide a line of code to submit your appid and appkey, that might be the problem :
Buddy.Init("yourAppId", "yourAppKey");
My guess is you have to use their .NET SDK!
You can certainly use the REST API from raw REST the way you're doing, though the .NET SDK will handle some of the more complex details of changing service root. I ran your code using my own Buddy credentials and I was able to get JSON containing an Access Token back. You may need to read the response stream back as JSON to retrieve the access token. I used the following code to dump the JSON to the console:
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
Console.WriteLine(await new StreamReader(response.GetResponseStream()).ReadToEndAsync());
Using Newtonsoft.Json I can parse out my accessToken like this:
Uri url = new Uri("https://api.buddyplatform.com/devices");
request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
sw.WriteLine(parameters);
sw.Close();
response = (HttpWebResponse)await request.GetResponseAsync();
var parsed = JsonConvert.DeserializeObject<IDictionary<string,object>>( (await new StreamReader(response.GetResponseStream()).ReadToEndAsync()));
var accessToken = (parsed["result"] as JObject).GetValue("accessToken").ToString();
Console.WriteLine(accessToken);
The 3.0 SDK does all of this for you while exposing the rest of the service through a thin REST wrapper, the migration guide for the 3.0 SDK should help with this.

403 error response when submitting a post request to Instagram

I'm trying to "programmatically" login to Instagram with a HTTP post request. Although, whenever I try to do it to this URL: https://instagram.com/accounts/login/ - it gives me a 404 error. However, if I remove the slash from the end, e.g. /accounts/login, then it will work, however, the response body just seems to be a simple GET request as they simply just output the same as if it was a GET request. I'm actually expecting an error message as response.
The code is written in C# and is nothing fancy; basically a http web request and then I write the post data in the TCP stream. The website is using a CSRF token which needs to be included in the post request, so I first grab this key by using a simple GET request, and then continuing with the POST.
Is there any technical aspect that I'm missing? I've tried the code and done the same on several other websites and all attempts were successful.
The code looks much like this (same problem):
WebResponse Response;
HttpWebRequest Request;
Uri url = new Uri("https://instagram.com/accounts/login/");
CookieContainer cookieContainer = new CookieContainer();
Request = (HttpWebRequest)WebRequest.Create(url);
Request.Method = "GET";
Request.CookieContainer = cookieContainer;
// Get the first response to obtain the cookie where you will find the "csrfmiddlewaretoken" value
Response = Request.GetResponse();
string Parametros = "csrfmiddlewaretoken=" + cookieContainer.GetCookies(url)["csrftoken"].Value + "&username=USER&password=PASSWORD&next="; // This whill set the correct url to access
Request = (HttpWebRequest)WebRequest.Create(url); // it is important to use the same url used for the first request
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.UserAgent = "Other";
// Place the cookie container to obtain the new cookies for further access
Request.CookieContainer = cookieContainer;
Request.Headers.Add("Cookie",Response.Headers.Get("Set-Cookie")); // This is the most important step, you have to place the cookies at the header (without this line you will get the 403 Forbidden exception
byte[] byteArray = Encoding.UTF8.GetBytes(Parametros);
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Response = Request.GetResponse(); // Fails here
Thanks in advance!

C# API POST Request

I'm trying to post to an API using C#.
Here is some documentation on the API: http://docs.gurock.com/testrail-api/accessing
Here is what I have so far:
string url = "https://example.testrail.com//index.php?/miniapi/add_result/1&key=19e73cdd99fbad172d3523b13d1c8c8f";
HttpWebRequest req = WebRequest.Create(new Uri(url))as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
My question is how can I pass in a Status_id of 1 and a comment of "Test" and then post to the API?
You need to call the GetRequestStream method on your req object, and write the post parameters to that

Categories

Resources