Connecting to Twitter - RestSharp OAuth2 - twitter

I am attempting to connect to the Twitter API with these instructions
https://dev.twitter.com/docs/auth/application-only-auth
Here is my code:
var baseUrl = "http://api.twitter.com/";
var client = new RestClient(baseUrl);
var request = new RestRequest("/oauth2/token", Method.POST);
var concat = ConfigurationManager.AppSettings["TwitterConsumerKey"] + ":" +
ConfigurationManager.AppSettings["TwitterConsumerSecret"];
string encodeTo64 = concat.EncodeTo64();
request.AddHeader("Authorization", "Basic " + encodeTo64);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.AddBody("grant_type=client_credentials");
IRestResponse restResponse = client.Execute(request);
EncodeTo64
static public string EncodeTo64(this string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
Response.Content is the following
"{\"errors\":[{\"code\":170,\"label\":\"forbidden_missing_parameter\",\"message\":\"Missing required parameter: grant_type\"}]}"
Is this part wrong?
request.AddBody("grant_type=client_credentials");
I have verified that my credentials are correct (I got that error before, but resolved it, so it should be OK).

The instructions on the Twitter page confused me. "The body of the request must be grant_type=client_credentials."
As for Restsharp, it's not AddBody, but AddParameter.
So:
request.AddParameter("grant_type", "client_credentials");

Related

Microsoft Graph API Authentication_MissingOrMalformed

I am using oauth2/token to authenticate my application and get the access_token. Bellow is the java code which is working fine.
private String getToken() throws Exception {
String access_token = "";
String url = "https://login.windows.net/MyApplication_ID_here/oauth2/token";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
urlParameters.add(new BasicNameValuePair("client_id", "MyApplication_ID_here"));
urlParameters.add(new BasicNameValuePair("client_secret", "MyApplication_secret_here"));
urlParameters.add(new BasicNameValuePair("resource", "https://graph.microsoft.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
String responseAsString = EntityUtils.toString(response.getEntity());
System.out.println(responseAsString);
try {
access_token = responseAsString.split(",")[6].split("\"")[3]; // get the access_token from response
} catch (Exception e) {
e.printStackTrace();
return null;
}
return access_token;
}
Response :
{"token_type":"Bearer","expires_in":"3599","ext_expires_in":"0","expires_on":"1493011626","not_before":"1493007726","resource":"https://graph.microsoft.com","access_token":"eyJ0e..."}
then I am using access_token to load the memberOf value which is not working and gives me the Access Token missing or malformed error. Bellow is the java code
private void getMemberOf()
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.addHeader("Authorization", "Bearer " + access_token);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
e.getMessage();
}
}
Response :
Response Code : 401
{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2017-04-24T04:39:38","requestId":"c5aa2abe-9b37-4611-8db1-107e3ec08c14","values":null}}
Can someone please tell me which part of the above request is wrong? Am I not setting access_token correctly?
According to your code , your access token is for resource "https://graph.microsoft.com"(Microsoft Graph API) ,But the access token is used for "https://graph.windows.net"(AAD Graph API) :
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
If you want to call Azure AD graph api , you need to get access token for Azure AD Graph API .
I got this issue while performing the CRUD operation on Azure AD B2C service via AD Graph API for user management.
The idea is to get the access token for the resource "graph.windows.net" instead I was using my tenant App Id URI as it was suggested here.
*might help people who faced the same issue and landed up here

RestSharp / MailChimp 'API key missing' error

When I post a campaign on Mailchimp using RestSharp, it tells me my API key is missing, but when I click "Get Campaign", it successfully shows me all the campaign data.
Can anyone tell me where I'm going wrong? Here's my code:
public MailChimpPostModel PostCampaign(MailChimpPostModel post)
{
var auth = _userBusinessObject.GetUserWebsiteAuthorizationByWebsite(_userId,
_websiteId,
_linkvanaNetworkSiteId);
ApiBaseUrl = <url> ;
if (auth == null)
throw new RestRequestResponseException { Error = RestErrorsEnum.NotAuthenticated };
var request = new RestRequest(3.0/campaigns, Method.POST);
request.AddParameter("access_token", <Token>);
request.AddParameter("apikey", <Token> + "-" + <dc>);
request.AddHeader("content-type", "application/json");
request.AddBody(post);
var response = Execute<MailChimpPostModel>(request);
return response;
}
// replace usX to match the last 3 of your API
var client = new RestClient("https://usX.api.mailchimp.com/3.0/");
client.Authenticator = new HttpBasicAuthenticator("user", APIKey);

Bad request 400 when exchanging refresh_token for access_token with box.com

I have successfully done this in the past for other services, however with box.com I get an error and I've tried everything I could think off and that others have suggested here.
I'm using .NET C#;
string postdata = "";
postdata += "client_id=" + HttpUtility.UrlEncode(client_id) + "&";
postdata += "client_secret=" + HttpUtility.UrlEncode(client_secret) + "&";
postdata += "refresh_token=" + HttpUtility.UrlEncode(refreshToken) + "&";
postdata += "redirect_uri=" + HttpUtility.UrlEncode(_redirectUri) + "&";
postdata += "grant_type=refresh_token";
var json = PostResponse(new Uri(#"https://www.box.com/api/oauth2/token"), postdata);
I've tried both with and without urlencoding of the values. Normally urlencoding is not needed in my experience.
I've also tried different order of parameters.
private string PostResponse(Uri uri, string postdata)
{
var bytes = Encoding.UTF8.GetBytes(postdata);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = bytes.Length;
Stream OutputStream = request.GetRequestStream();
OutputStream.Write(bytes, 0, bytes.Length);
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
This code fails with error 400 (bad request). Similar code works fine with for example Google Drive.
Can anyone spot what I'm doing wrong with box.com? Thanks!
Got it working using box_device_id and box_device_name (indirectly part of my problem) plus examining the response in details which showed that a json error message was returned stating that the refresh token had expired. Turns out that Box expires refresh tokens when using them, issuing a new one. This is different from the other cloud drives I've integrated with.

Oauth not working CX api

I'm trying to use the oauth for CX exposed api, I followed their documentation, still I'm getting HTTP "BAD REQUEST" error, Here is the code -
String method = "POST";
String code = "";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", code),
new NameValuePair("redirect_uri",URLEncoder.encode(CALLBACK_URL, "UTF-8"))
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
httpClient.executeMethod(httpMethod);
Thanks,
Hemant
I've tested the following slight modification of your code and it works. You might double check that
Your key has been approved (this shouldn't be the problem given the
error you are seeing).
You are using the correct ACCESS_TOKEN_ENDPOINT_URL
Try having the redirect_uri be the same for both the auth_code response and the token request
String method = "POST";
String authCode = "[AUTH-CODE-HERE]";
String CONSUMER_KEY="[YOUR-KEY-HERE]";
String CONSUMER_SECRET="[YOUR-SECRET-HERE]";
String ACCESS_TOKEN_ENDPOINT_URL="https://api.cx.com/1/oauth/token";
String REDIRECT_URI="[YOUR-REDIRECT-HERE]";
NameValuePair[] data = {
new NameValuePair("grant_type", "authorization_code"),
new NameValuePair("code", authCode),
new NameValuePair("redirect_uri", REDIRECT_URI)
};
String secret = CONSUMER_KEY+":"+CONSUMER_SECRET;
String encodedSecret = Base64.encodeBase64String(secret.getBytes("UTF-8"));
PostMethod httpMethod = new PostMethod(ACCESS_TOKEN_ENDPOINT_URL);
httpMethod.addRequestHeader("Authorization","Basic "+encodedSecret);
httpMethod.setRequestBody(data);
System.out.println("HTTP call -- " + method + " " + ACCESS_TOKEN_ENDPOINT_URL);
int responseCode = httpClient.executeMethod(httpMethod);
System.out.println(responseCode);
System.out.println(httpMethod.getResponseBodyAsString());
If you are still running into issues, can you post the result of the following line: System.out.println(httpMethod.getResponseBodyAsString());
The CX developer API has been discontinued.
Sorry for the inconvenience.

Google Places API: Adding a new Place: Java/Groovy

Can't get the POST working? What's wrong?
Note: This works for a GET with autocomplete
GET works without signing the url
I'm following the Web services steps to Sign the URL with my "API Key"
Docs say"client id" still?
http://code.google.com/apis/maps/documentation/webservices/
2.Try sending the POST data with the signed URL (tried the unsigned signature aswell)
def signedUrl = "https://maps.googleapis.com/maps/api/place/add/json?key=xxxxxkeyxxxxxx&sensor=false&signature=xxxxxxxxxxsignaturexxxxxx"
String postData = "{'location': { 'lat': '-33.8669710','lng': '151.1958750'},'accuracy': '50','name': 'Google Shoes!'}"
URL urlPost = new URL(signedUrl);
URLConnection connection = urlPost.openConnection();
connection.addRequestProperty("Referer", "http://www.mysite.com");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("CONTENT-TYPE", "text/json");
connection.setRequestProperty("CONTENT-LENGTH", postData.length() + "");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(postData);
out.close();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
println json
Returns a 403
"java.io.IOException: Server returned HTTP response code: 403 for URL:"
Simular to the "Java Access"section under they give an example of a GET
http://code.google.com/apis/websearch/docs/#fonje
Ok solved.
No signing the URL required
postData string was wrong
should have been
String postData = "{\"location\": { \"lat\": -33.8669710,\"lng\": 151.1958750},\"accuracy\": 50,\"name\": \"Google Shoes!\", \"types\":[\"bar\"]}"

Resources