Using twitter to get bearer token - twitter

I'm using the following code to return the bearer token but i keep getting
"The remote server returned an error: (500) internal server error" on line
"WebResponse response = request.GetResponse();"
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");
string consumerKey = "31111111111111111111";
string consumerSecret = "1111111111111111111111A";
string consumerKeyAndSecret = String.Format("{0}:{1}", consumerKey, consumerSecret);
request.Method = "POST";
request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.Unicode.GetBytes(consumerKeyAndSecret))));
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Any advise would be amazing

I found the solution after wasting many hours.
This error will rise because of the base64 encoding using Unicode. Just change the UNICODE to UTF8, and nothing else.
Final code:
WebRequest request = WebRequest.Create("https://api.twitter.com/oauth2/token");
string consumerKey = "31111111111111111111";
string consumerSecret = "1111111111111111111111A";
string consumerKeyAndSecret = String.Format("{0}:{1}", consumerKey, consumerSecret);
request.Method = "POST";
request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKeyAndSecret))));
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();

In the past I have used TweetSharp that uses Twitter's 1.1 API. You'd probably be better using that for your twitter calls.
TweetSharp Github: https://github.com/danielcrenna/tweetsharp
If you require an example or what you need, let me know.

Related

How to set security/Authorisation Token in Post request of Rest Assured using selenium

Please suggest how i can set Security token for below code
RestAssured.baseURI ="http://qa.bridge2capital.com";
RestAssured.port = 9099;
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("UserName", "10111");
requestParams.put("Password", "123568");
request.header("Content-Type", "application/json");
request.body(requestParams.toString());
Response response = request.post("/entrepreneur/consolidatedEodTrigger");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "200");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Correct Success code was returned", successCode, "OPERATION_SUCCESS");
You can use below code to set basic token:
request.header("Authorization", "Basic " + yourToken);
According to your answer you should try
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("UserName", "10111");
requestParams.put("Password", "123568");
request.header("Content-Type", "application/json");
request.header("Authorization", "Basic " + base64encodedToken); //This is the important line
request.body(requestParams.toString());
Response response = request.post("/entrepreneur/consolidatedEodTrigger");
int statusCode = response.getStatusCode();
Assert.assertEquals(statusCode, "200");
String successCode = response.jsonPath().get("SuccessCode");
Assert.assertEquals( "Correct Success code was returned", successCode, "OPERATION_SUCCESS");

Discogs api oauth: authenticate/identity

I'm trying to build a .net program that helps me organizing my vinyls. For that I use the discogs API. I'm having problems with the oauth procedure. The first 4 steps were succesful; I received an access_token and access_token_secret (using the request_token, request_token_secret and verifier). Only the last step is giving me problems: the identity check to see if I (the user) am succesfully authorized. According to the discogs APi documentation it should be enought to send the access_token and access_token_secret to /oauth/identity but I keep getting a '502 bad gateway' response.
This is the request I send:
Public Function makeTestRequest()
Dim requestResult As String = ""
Dim user_agent As String = "ll// .01 DiscogsTestApp"
Dim oauth_consumer_key As String = "AAA"
Dim oauth_token As String = "BBB"
oauth_signature_method = "PLAINTEXT"
Dim oauth_signature As String = "CCC&" & "DDD"
oauth_timestamp = setTimeStamp()
oauth_nonce = setNounce()
'Set authorization header
Dim headerFormat As String = "OAuth oauth_consumer_key=""{0}"",oauth_nonce=""{1}"",oauth_token""{2}"",oauth_signature""{3}"",oauth_signature_method""{4}"",oauth_timestamp""{5}"""
'Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_version))
'set the request
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim streamReader As System.IO.StreamReader
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim requestUrl3 As String = "http://api.discogs.com/oauth/identity"
request = WebRequest.Create(requestUrl3)
request.Accept = "application/json, text/plain, */*"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = 0
request.Method = "GET"
request.UserAgent = "user_agent"
request.Timeout = -1
request.Headers.Add("Authorization", authHeader)
Try
response = DirectCast(request.GetResponse, HttpWebResponse)
streamReader = New System.IO.StreamReader(response.GetResponseStream(), encode)
requestResult = streamReader.ReadLine
request.Abort()
streamReader.Close()
streamReader = Nothing
response.Close()
response = Nothing
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return requestResult
End Function
As you see I send more than just access_token and secret (according to this example)
So this keeps giving me a '502 bad gateway' response... Does anyone have an idea what is causing this? Perhaps any ideas that I can try?
Just for info: the post request for requesting access_token works fine, here is the code:
Public Function makeFinalRequest()
Dim requestResult As String = ""
oauth_nonce = setNounce()
oauth_timestamp = setTimeStamp()
Dim oauth_signature As String = Form1.txtconsumer_secret.Text & Form1.txtoauth_token_secret.Text
oauth_consumer_key = Form1.txtconsumer_key.Text
oauth_signature_method = "PLAINTEXT"
Dim oauth_token As String = Form1.txtoauth_token.Text
Dim oauth_verifier As String = Form1.txtverifier.Text
Dim user_agent As String = "ll// .01 DiscogsTestApp"
oauth_token_secret = Form1.txtoauth_token_secret.Text
Dim oauth_version As String = "1.0"
'Set authorization header
Dim headerFormat As String = "OAuth oauth_consumer_key=""{0}"", oauth_nonce=""{1}"",oauth_token=""{2}"",oauth_signature=""{3}"",oauth_signature_method=""{4}"",oauth_timestamp=""{5}"",oauth_verifier=""{6}"",oauth_version=""{7}"""
Dim authHeader As String = String.Format(headerFormat, Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_verifier), Uri.EscapeDataString(oauth_version))
'set the request
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim streamReader As System.IO.StreamReader
Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim requestUrl2 As String = "https://api.discogs.com/oauth/access_token"
request = WebRequest.Create(requestUrl2)
request.UserAgent = user_agent
request.Accept = "application/json, text/plain, */*"
request.Method = "POST"
'request.ContentLength =
request.Timeout = -1
request.ContentLength = 0
request.Headers.Add("Authorization", authHeader)
Try
response = DirectCast(request.GetResponse, HttpWebResponse)
streamReader = New System.IO.StreamReader(response.GetResponseStream(), encode)
requestResult = streamReader.ReadLine
request.Abort()
streamReader.Close()
streamReader = Nothing
response.Close()
response = Nothing
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Return requestResult
End Function
Please let me know if I need to post more details...
Any help is much appreciated!
Thanks

Oauth2 Yahoo Gemini API

I am having trouble calling Yahoo Gemini API to access Yahoo Gemini Advertising from my C# console (desktop) application.
Here are steps I used:
Create an installed application on https://developer.yahoo.com/apps/create/. This gave me both {Client ID} and {Client Secret}.
https://api.login.yahoo.com/oauth2/request_auth?client_id={Client ID} &redirect_uri=oob&response_type=code&language=en-us. This will take me to the yahoo login screen where I sign in. Press the Agree button and the next screen shows the seven-letter authorization code (say nzbcns9). I write down this authorization code.
Then I use the following code to try to get the access token:
class Program
{
static void Main(string[] args)
{
string clientId = {Client ID};
string secret = {Client Secret};
var request = WebRequest.Create(#"https://api.login.yahoo.com/oauth2/get_token");
request.Method = "POST";
SetBasicAuthHeader(request, clientId, secret);
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
request.ContentType = "application/x-www-form-urlencoded";
var response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
}
static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
}
Then I get
Unhandled Exception: System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse().
What did I do wrong?
I also try to post the same message using Fiddler, I get
{"error":"invalid_request"}
I tried your code and what worked for me was to put the line request.ContentType = "application/x-www-form-urlencoded"; BEFORE Stream dataStream = request.GetRequestStream();
So this worked:
string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
request.ContentLength = byte1.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byte1, 0, byte1.Length);
dataStream.Close();
Neither of these worked for me, but it did work once I changed the SetBasicAuthHeader to use ISO-8859-1 encoding:
static void SetBasicAuthHeader( WebRequest request, String userName, String userPassword )
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String( Encoding.GetEncoding( "ISO-8859-1" ).GetBytes( authInfo ) );
request.Headers[ "Authorization" ] = "Basic " + authInfo;
}

Parse push REST API error 400 "Bad Request"

I am developing an app for iOS using Xamarin iOS & MonoGame. I want to use Parse's push notifications through their REST API, so first I must create an installation object:
var bundle = new Dictionary<string, object>();
bundle.Add("channels", "");
bundle.Add("deviceType", "ios");
bundle.Add("deviceToken", _deviceToken);
string urlpath = "https://api.parse.com/1/installations";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("X-Parse-Application-Id", _parseAppID);
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", _parseRestAPIKey);
httpWebRequest.Method = "POST";
string bundleString = bundle.ToJson();
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(bundleString);
string result = Convert.ToBase64String(buffer);
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(result, 0, result.Length);
requestWriter.Close();
WebResponse httpResponse = await httpWebRequest.GetResponseAsync();
Stream stream = httpResponse.GetResponseStream();
string json = string.Empty;
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json += reader.ReadLine();
}
}
JsonObject jsonObject = JsonObject.Parse(json);
_varStorage.Save("ObjectId", jsonObject.Get<string>("objectId"));
The bundleString value is:
"{\"channels\":\"\",\"deviceType\":\"ios\",\"deviceToken\":\"46becd0a165be042eeab5a1ec96b8858065cbea7311479da16c0fd1c9428e2eb\"}"
This code raises a System.Net.WebExceptionStatus.ProtocolError error 400 "Bad Request", and I can't see why.
Channels is supposed to be an array of strings according to the documentation, https://www.parse.com/docs/rest#installations
bundle.Add("channels", new [] { "" });
After more trail and error, I found that replacing this
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(bundleString);
string result = Convert.ToBase64String(buffer);
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(result, 0, result.Length);
requestWriter.Flush();
requestWriter.Close();
with this
httpWebRequest.ContentLength = bundleString.Length;
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(bundleString);
requestWriter.Flush();
requestWriter.Close();
fixed the problem, I don't know exactly why though.
should you not be calling flush before closing your stream ?
requestWriter.Write(result, 0, result.Length);
requestWriter.Close();

Get Accesstoken Token Error in Box Oauth

please help to Get accesstoken after get code i am request to get accesstoken through following code in C# but it always return me The remote serve (400) bad request
curl https://www.box.com/api/oauth2/token \
-d 'grant_type=authorization_code&code={your_code}&client_id={your_client_id}&client_secret={your_client_secret}' \
-X POST
Here is the code I'm using :
Stream stream = null;
WebRequest webRequest = null;
StreamReader streamReader = null;
WebResponse webResponse = null;
webRequest = WebRequest.Create("box.com/api/oauth2/token");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
byte[] data = Encoding.GetEncoding("UTF-8").GetBytes("'grant_type=authorization_code&code={myc??ode}&client_id={myclient_id}&client_secret={myclient_secret}'");
webRequest.ContentLength = data.Length;
Stream reqstr = webRequest.GetRequestStream();
reqstr.Write(data, 0, data.Length);
reqstr.Close();
webResponse = webRequest.GetResponse();
stream = webResponse.GetResponseStream();
streamReader = new StreamReader(stream);
WebResponseData = streamReader.ReadToEnd();

Resources