Oauth2 Yahoo Gemini API - oauth-2.0

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

Related

passing access token to Jira using OAuth Authentication

I am using OAuth authenication in Jira to test some methods in jira using JIRA Rest Java Client. I have got the access token using OAuth authenication that I need to pass on Jira URL. Here is all what I have got to get access token.
Token is 38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Token secret is cnDSL8oJyuoaQdRcFDwgHzLppSshQn9b
Retrieved request token. go to http://bmh1060149:8080/plugins/servlet/oauth/authorize?oauth_token=38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Access token is : 015CeJiH8cpI5R3OKpNco158kApq8YwV
Now I am passing that access token to Jira URL but I am getting an empty array. Please let me know where I am doing wrong or what changes do I need to incorporate into my code to make this thing work. Here is my code.
public void getAllIssueTypesUsingOAuth(JiraCQCredential jcqcred) {
System.out.println("Inside getAllIssuetypeAssociatedToProject for JiraAdapterImpl");
//String username = jcqcred.getUserName();
//String password = jcqcred.getPassword();
String jiraURL = jcqcred.getJiraUrl();
if (!jiraURL.endsWith("/")) {
jiraURL = jiraURL + "/";
}
try {
String accessToken = JiraAdapterImpl.getAccessToken(); // This method is giving me access token
URL url = new URL(jiraURL + "rest/api/2" + "/" + "issuetype?access_token=" + accessToken);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String issueTypes = sb.toString();
System.out.println("Issuetype associated to project are\n" + issueTypes);
JSONArray jsonArray = new JSONArray(issueTypes);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String issueNames = (String) jsonObject.get("name");
System.out.println(issueNames);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Its giving me an empty array like []
Hi After searching the little bit I finally managed to a find the solution to the above problem. After getting the access token just pass that access token to the makeAuthenticatedRequest(url, accessToken) method that will give you the resultant data which you want to retrive. Here url is the url which you want to hit to get the resultant data.
private AtlassianOAuthClient getJiraOAuthClient() {
final String baseURI = "http://bmh1060149:8080";
final String consumerKey = "hardcoded-consumer";
final String consumerPrivatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFkPMZQaTqsSXI+bSI65rSVaDzic6WFA3WCZMVMi7lYXJAUdkXo4DgdfvEBO21Bno3bXIoxqS411G8S53I39yhSp7z2vcB76uQQifi0LEaklZfbTnFUXcKCyfwgKPp0tQVA+JZei6hnscbSw8qEItdc69ReZ6SK+3LHhvFUUP1nLhJDsgdPHRXSllgZzqvWAXQupGYZVANpBJuK+KAfiaVXCgA71N9xx/5XTSFi5K+e1T4HVnKAzDasAUt7Mmad+1PE+56Gpa73FLk1Ww+xaAEvss6LehjyWHM5iNswoNYzrNS2k6ZYkDnZxUlbrPDELETbz/n3YgBHGUlyrXi2PBjAgMBAAECggEAAtMctqq6meRofuQbEa4Uq5cv0uuQeZLV086VPMNX6k2nXYYODYl36T2mmNndMC5khvBYpn6Ykk/5yjBmlB2nQOMZPLFPwMZVdJ2Nhm+naJLZC0o7fje49PrN2mFsdoZeI+LHVLIrgoILpLdBAz/zTiW+RvLvMnXQU4wdp4eO6i8J/Jwh0AY8rWsAGkk1mdZDwklPZZiwR3z+DDsDwPxFs8z6cE5rWJd2c/fhAQrHwOXyrQPsGyLHTOqS3BkjtEZrKRUlfdgV76VlThwrE5pAWuO0GPyfK/XCklwcNS1a5XxCOq3uUogWRhCsqUX6pYfAVS6xzX56MGDndQVlp7U5uQKBgQDyTDwhsNTWlmr++FyYrc6liSF9NEMBNDubrfLJH1kaOp590bE8fu3BG0UlkVcueUr05e33Kx1DMSFW72lR4dht1jruWsbFp6LlT3SUtyW2kcSet3fC8gySs2r6NncsZ2XFPoxTkalKpQ1atGoBe3XIKeT8RDZtgoLztQy7/7yANQKBgQDQvSHEKS5SttoFFf4YkUh2QmNX5m7XaDlTLB/3xjnlz8NWOweK1aVysb4t2Tct/SR4ZZ/qZDBlaaj4X9h9nlxxIMoXEyX6Ilc4tyCWBXxn6HFMSa/Rrq662Vzz228cPvW2XGOQWdj7IqwKO9cXgJkI5W84YtMtYrTPLDSjhfpxNwKBgGVCoPq/iSOpN0wZhbE1KiCaP8mwlrQhHSxBtS6CkF1a1DPm97g9n6VNfUdnB1Vf0YipsxrSBOe416MaaRyUUzwMBRLqExo1pelJnIIuTG+RWeeu6zkoqUKCAxpQuttu1uRo8IJYZLTSZ9NZhNfbveyKPa2D4G9B1PJ+3rSO+ztlAoGAZNRHQEMILkpHLBfAgsuC7iUJacdUmVauAiAZXQ1yoDDo0Xl4HjcvUSTMkccQIXXbLREh2w4EVqhgR4G8yIk7bCYDmHvWZ2o5KZtD8VO7EVI1kD0z4Zx4qKcggGbp2AINnMYqDetopX7NDbB0KNUklyiEvf72tUCtyDk5QBgSrqcCgYEAnlg3ByRd/qTFz/darZi9ehT68Cq0CS7/B9YvfnF7YKTAv6J2Hd/i9jGKcc27x6IMi0vf7zrqCyTMq56omiLdu941oWfsOnwffWRBInvrUWTj6yGHOYUtg2z4xESUoFYDeWwe/vX6TugL3oXSX3Sy3KWGlJhn/OmsN2fgajHRip0=";
AtlassianOAuthClient jiraoAuthClient = new AtlassianOAuthClient(consumerKey, consumerPrivatekey, baseURI, "");
return jiraoAuthClient;
}
Here is the code to get Access Token
private String getAccessToken() {
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
TokenSecretVerifierHolder requestToken = jiraoAuthClient.getRequestToken();
String authorizeUrl = jiraoAuthClient.getAuthorizeUrlForToken(requestToken.token);
String token = requestToken.token;
String tokenSecret = requestToken.secret;
System.out.println("Token is " + requestToken.token);
System.out.println("Token secret is " + requestToken.secret);
System.out.println("Retrieved request token. go to " + authorizeUrl);
String accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, "");
System.out.println("Access token is : " + accessToken);
return accessToken;
}
This is the method you call to retrieve the data.
public void getAllCommentOfIssueUsingOAuth() {
logger.info("Inside getAllCommentOfIssue for JiraAdapterImpl");
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
String accessToken = getAccessToken();
String url = "your Jira URL";
String responseAsString = jiraoAuthClient.makeAuthenticatedRequest(url, accessToken);
System.out.println(responseAsString);
}
This will give you the resultant JSON data or XML data in resultantString.

Twilio send sms api request using http post mentod in asp.net

I am learning twilio send sms tool.
I want to make post url request for send message in asp.net mvc application.
I tired some code but could not get safisfied o/p.
There is an error that is authentication sid or auth token is invalid.
Can anyone help me how to make post request for twilio send sms api?
try{
const string accountSid = "AC255e61580d73904b2a5e5a5e39c715f0";
const string authToken = "AUTH_TOKEN";
const string url = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json";
TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
var authInfo = accountSid +":"+ authToken;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Method = "POST";
var postData = "{\"To\":" + "\"" + sms.ToNumber + "\"" + ", \"From\":" + "\"" + fromNumber + "\"" + ", \"Body\":" + "\"" + sms.Body + "\"}";
var data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream writer = null;
writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
request.Headers["Authorization"] = "Basic " + authInfo;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
msg = client.SendMessage("+12012317746 ", sms.ToNumber,sms.Body);
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string err =reader.ReadToEnd();
}
}
I have an error :
{"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}
Please check if you are using the Live credentials(accountSid,authToken) on your Twilio Account.
The API does the post already:
https://www.twilio.com/docs/api/twiml/sms/twilio_request
You don't need all this code below.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
var authInfo = accountSid +":"+ authToken;
authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
request.Method = "POST";
var postData = "{\"To\":" + "\"" + sms.ToNumber + "\"" + ", \"From\":" + "\"" + fromNumber + "\"" + ", \"Body\":" + "\"" + sms.Body + "\"}";
var data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream writer = null;
writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
request.Headers["Authorization"] = "Basic " + authInfo;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();

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

SurveyMonkey returning unexpected EOF error exchanging authorization code for access token

Code that had been working in a "localhost" environment is failing after deploying it to production under (obviously) a new callback URL. Nothing else was changed. The request to SurveyMonkey's API to exchange the Authorization Code for a long-lived Access Token is returning this error:
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.
Is there something else that needs to be changed, maybe to a production client_id ? Please advise, we are stuck.
Here is the code:
var clientId = _sds.ByName("SurveyMonkeyClientID").Value;
var apiSecret = _sds.ByName("SurveyMonkeyAPISecret").Value;
var callbackURL = _sds.ByName("SurveyMonkeyCallbackURL").Value;
var accessTokenUri = "https://api.surveymonkey.net/oauth/token?api_key=" + _sds.ByName("SurveyMonkeyAPIKey").Value;
// Create postback data
var postData = new NameValueCollection()
{
{ "client_secret", apiSecret },
{ "code", authorizationCode },
{ "redirect_uri", callbackURL },
{ "client_id", clientId },
{ "grant_type", "authorization_code" }
};
var queryString = string.Join("&", (
from key in postData.AllKeys
from value in postData.GetValues(key)
select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))).ToArray()
);
// Create and configure the web request object
var request = WebRequest.Create(accessTokenUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var dataStream = request.GetRequestStream();
var postArray = Encoding.UTF8.GetBytes(queryString);
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
// Make the call to Survey Monkey's token exchange uri
try
{
var response = request.GetResponse();
dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
SaveSurveyMonkeyJsonWhole(responseFromServer);
dynamic jobject = _serializer.DeserializeObject(responseFromServer);
var access_token = jobject["access_token"];
return access_token;
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
return string.Empty;
}

Using twitter to get bearer token

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.

Resources