LinkedIn RestSharp and OAuthBase Example - oauth-2.0

anyone ever used C# in combination with the library RestSharp and OAuthBase in order get some interaction with LinkedIn?
I'm looking for a working example using these tools to do proper authorization (oAuth 2.0) and to publish a post using the share API on LinkedIn.
So far I've been successful using these tools to obtain valid access tokens (I can use it to obtain profile information for example), but posting via the share API got me stuck on authentication.
Any help would be very much appreciated!!

it turned out to be much simpler than I was thinking.... (doesn't it allways?)
The main point to take into account is: oAuth 2.0 does not require signatures, nonce, timestamps, authorization headers ... none of that.
If you want to post on LinkedIn using the sahres API and using oAuth2.0 ... OAuthbase is not needed.
Simply follow the oauth 2.0 authentication flow as described here:
http://developer.linkedin.com/documents/authentication
And then you can use the following code as a starting point:
var shareMsg = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new
{
title = "Test post to LinkedIn",
submitted_url = "http://www.somewebsite.com",
submitted_image_url = "http://www.somewebsite.com/image.png"
},
visibility = new
{
code = "anyone"
}
};
String requestUrl = "https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=" + accessToken;
RestClient rc = new RestClient();
RestRequest request = new RestRequest(requestUrl, Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = DataFormat.Json;
request.AddBody(shareMsg);
RestResponse restResponse = (RestResponse)rc.Execute(request);
ResponseStatus responseStatus = restResponse.ResponseStatus;
Happy coding!!

Related

Youtube API C# Error, cant post comment? What else should I do

async Task AddVideoCommentAsync(string commentToAdd, string videoID, YouTubeService youtubeService)
{
CommentSnippet commentSnippet = new CommentSnippet();
commentSnippet.TextOriginal = commentToAdd;
Comment topLevelComment = new Comment();
topLevelComment.Snippet = commentSnippet;
CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet();
commentThreadSnippet.ChannelId = "UCsK0terzCGmIPAeGmW-i-VA";
commentThreadSnippet.VideoId = videoID;
commentThreadSnippet.TopLevelComment = topLevelComment;
CommentThread commentThread = new CommentThread();
commentThread.Snippet = commentThreadSnippet;
CommentThreadsResource.InsertRequest insertComment = youtubeService.CommentThreads.Insert(commentThread, "snippet");
await insertComment.ExecuteAsync();
}
This is my Code to Insert a comment on a video of my choice.
What is wrong here? I got this code from another question on here and changed it a bit, but:
Error: Google.Apis.Requests.RequestError
Request had insufficient authentication scopes. [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]```
According to the official doc of the CommentThreads.insert API endpoint, a prerequisite of calling it is the following:
Authorization
This request requires authorization with at least one of the following scopes (read more about authentication and authorization).
Scope
https://www.googleapis.com/auth/youtube.force-ssl
Therefore, your youtubeService should have been initialized by means of credentials obtained upon an OAuth 2.0 authentication/authorization flow and those credentials should have had attached among their scopes the one specified above.

OAuth1 Authentication in RestSharp for Twitter API GET and POST methods

Using Postman I'm successfully able to query and create tailored audiences using the Twitter API, using Postman's OAuth 1.0 Authorization. However when trying to do the same with RestSharp I get an Unauthorized error.
"UNAUTHORIZED_ACCESS" - "This request is not properly authenticated".
My GET request authenticates fine, but the POST request fails.
_twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
};
var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
//this works and gives me a list of my tailored audiences
var response1 = _twitterRestClient.Execute(restRequest1);
var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences?name=SampleAudience2&list_type=EMAIL", TwitterAccountId), Method.POST);
// this results in an "Unauthorized" status code , and the message {\"code\":\"UNAUTHORIZED_ACCESS\",\"message\":\"This request is not properly authenticated\"}
var response2 = _twitterRestClient.Execute(restRequest2);
Turns out this is due to a quirk in RestSharp OAuth1 implementation. I think its related to this issue - https://www.bountysource.com/issues/30416961-oauth1-not-specifing-parameter-type . Part of creating an OAuth1 signature involves gathering all the parameters in the request and other details and then hashing it all. It looks like when the HTTP Method is a POST, then RestSharp is not expecting parameters in the querystring (which makes sense), its expecting them in the post body. Anyhow if you add parameters explicitly then they are picked up and the OAuth1 signing works. (Turns out the twitter API works if these params are in the post body, so I didn't need to explicitly add them to the query string). Updated code that now works:
_twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
};
var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
var response1 = _twitterRestClient.Execute(restRequest1);
var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.POST);
restRequest2.AddParameter("name", "SampleAudience2");
restRequest2.AddParameter("list_type", "EMAIL");
var response2 = _twitterRestClient.Execute(restRequest2);

Instagram API returning error when requesting access_token on Windows Phone

I've been trying to integrate the Instagram API in my app, but am stuck with the authentication. I had it working completely fine when I was just using the implicit flow version which gave me the access_token as part of the URI fragment.
However, now I'm changing to the server-side flow, in which I receive a code after the user logs in. I then post this code to the access token URL, which will then give me the access_token as well as certain information about the user, such as their username and profile picture link.
I am using the InstaSharp library, modifying the source code.
HttpClient client = new HttpClient { BaseAddress = new Uri(config.OAuthUri + "access_token/", UriKind.Absolute) };
var request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
request.AddParameter("client_secret", config.ClientSecret);
request.AddParameter("client_id", config.ClientId);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("redirect_uri", config.RedirectUri);
request.AddParameter("code", code);
return client.ExecuteAsync<OAuthResponse>(request);
After creating my request, it is formatted as so:
{Method: POST, RequestUri: 'https://api.instagram.com/oauth/access_token/?client_secret={CLIENT_SECRET}&client_id={CLIENT_ID}&grant_type=authorization_code&redirect_uri=http://instagram.com &code={CODE}', Version: 1.1, Content: , Headers: { }}
(I inserted the space between the redirect_uri and code because it wouldn't let me post the question otherwise)
Everything appears normal in the address, but I always receive an error in the retuned json file:
"{"code": 400, "error_type": "OAuthException", "error_message": "You must provide a client_id"}"
I have no clue what is causing this error. Any help is greatly appreciated!
Thanks!
Elliott
Are you using the latest version of InstaSharp? Fork it here. You can check the README.md there although it's a bit outdated and you need to tweak some config. Here's how you can do it with the latest version that is in github:
// create the configuration in a place where it's more appropriate in your app
InstaSharpConfig = new InstagramConfig(
apiURI, oauthURI, clientId, clientSecret, redirectUri);
// then here's a sample method you can have to initiate auth
// and catch the redirect from Instagram
public ActionResult instagramauth(string code)
{
if (string.IsNullOrWhiteSpace(code))
{
var scopes = new List<InstaSharp.Auth.Scope>();
scopes.Add(InstaSharp.Auth.Scope.likes);
var link = InstaSharp.Auth.AuthLink(
oauthURI, clientId, redirectUri, scopes);
// where:
// oauthURI is https://api.instagram.com/oauth
// clientId is in your Instagram account
// redirectUri is the one you set in your Instagram account;
// for ex: http://yourdomain.com/instagramauth
return Redirect(link);
}
// add this code to the auth object
var auth = new InstaSharp.Auth(InstaSharpConfig);
// now we have to call back to instagram and include the code they gave us
// along with our client secret
var oauthResponse = auth.RequestToken(code);
// save oauthResponse in session or database, whatever suits your case
// oauthResponse contains the field Access_Token (self-explanatory),
// and "User" that'll give you the user's full name, id,
// profile pic and username
return RedirectToAction("action", "controller");
}
Take note that you can split up the "instagramauth" method. Did it that way for brevity.

Google Script API + Oauth + Tumblr

Hello,
I'm trying to acess, perform a post, into Tumblr with Oauth api provided by Tumblr) http://tumblr.com/api). I'm using Google Script and I've tryied too many solutions but anyone worked. To implement i've basaed myself into this(https://developers.google.com/apps-script/articles/twitter_tutorial) Google script twitter tutorial, once on Tumblr API web page they say that twitter api is almost the same that tumblr.
Contextualizing,
I've already set the Oauth class methods with data below and substituted consumer and secret keys with values got from the api i've created.
var oauthConfig = UrlFetchApp.addOAuthService("tumblr");
oauthConfig.setAccessTokenUrl(
"http://www.tumblr.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"http://www.tumblr.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"http://www.tumblr.com/oauth/authorize");
oauthConfig.setConsumerKey(<i>consumerkey</i>);
oauthConfig.setConsumerSecret(<i>consumerSecret</i>);
Error,
The code below isnt working as it should be.
var requestData = {
"method": "POST",
"oAuthServiceName": "tumbler",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"https://api.tumblr.com/v2/blog/{blog}.tumblr.com/post?type=text&body=word",
requestData);
The Script to Twitter is almost the same and it works. Im able to perform tweets.
var result = UrlFetchApp.fetch(
"https://api.twitter.com/1/statuses/update.json?status=" + tweet,
requestData);
Response From Server
Request failed for returned code 400. Server response: {"meta":{"status":400,"msg":"Bad Request"},"response":{"errors":["Post cannot be empty."]}}
Possible Solutions
A possible solution can work using this information(got from tumblr.com/api):
OAuth
The API supports the OAuth 1.0a Protocol, accepting parameters via the Authorization header, with the HMAC-SHA1 signature method only. There's probably already an OAuth client library for your platform.
My question is, what am I doing wrong?(my post inst empty, i have 2 params). Had anyone had the same problem? Someone has suggestions?
Thank You.
I don't know anything about the tumblr api, but your http post is empty (the oAuth parameters aren't in the post body, they're advanced options), the body of the post needs to go in the "payload" parameter. See the section "Advanced parameters" in the docs. Or, as you aren't using the post can't you use a get request instead? Remove the method: POST parameter (GET is the default).
Thank You very much Daniel. It worked now!!
Everybody that want use Tumblr + Google Script API + oAuth can use de code below to perform posts.
I created I Google Spreadsheet and then a script there. Before to be able to post I neded to create and app into tumblr.com/api and get secret and consumer keys. Also I've deployed the Google script as an web app(ensure that the version is the last one(the final code)) before to create a new version. After that you go tu publish > deploy as web app !
That twitter tutorial I put on my first question is the only path you need to conclude your job.
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("tumblr");
oauthConfig.setAccessTokenUrl(
"http://www.tumblr.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"http://www.tumblr.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"http://www.tumblr.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "tumblr",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"http://api.tumblr.com/v2/blog/{your_blog}.tumblr.com/posts/queue",
requestData);
}
function doGet(e) {
var tweet = e.parameter.tumblr;
var app = UiApp.createApplication().setTitle("Approved");
var panel = app.createFlowPanel();
authorize();
var encodedTweet = encodeURIComponent(tweet);
var payload =
{
"body" : encodedTweet,
"type" : "text"
};
var requestData = {
"method" : "POST",
"oAuthServiceName": "tumblr",
"oAuthUseToken": "always",
"payload" : payload
};
try {
var result = UrlFetchApp.fetch(
"https://api.tumblr.com/v2/blog/{your_blog}.tumblr.com/post",
requestData);
panel.add(app.createLabel().setText("You have approved: \"" + tweet + "\""));
} catch (e) {
Logger.log(e);
panel.add(app.createLabel().setText(e));
}
app.add(panel);
return app;
}

How to Access twitter from Salesforce

I am struggling to get this done, I need to connect to twitter rest Api 1.1 to get user details, time line etc.
What I came across is:
I have a Twitter App with access token ,secrete etc.
Now how to use all that access token etc to send (GET or POST) request to Twitter from Salesforce. How to set header or how to authenticate request.
A tutorial would be very help full all I could find was tutorials for php etc I need it for "salesforce"
Note: I don't want to use a external lib
You should be able to do this directly from Apex using the HTTP REST library. Here is the first Google result for "salesforce apex twitter integration" with this sample code from Navatar_DbSup:
VF CODE:
<apex:inputTextarea id="tweetInput" onkeyup="return maxLength();" onKeyPress="return maxLength();" value="{!newTweet}" rows="2" cols="73"/>
<apex:commandButton id="tweetBtn" style="height:35px;" value="Tweet" action="{!postTweet}" />
Controller code:
*** post tweets into twitter*/
public String newTweet{get;set;}
public Void postTweet()
{
Http h = new Http();
HttpRequest req = new HttpRequest();
Method = 'POST';
req.setMethod(Method);
req.setEndpoint('https://api.twitter.com/1/statuses/update.xml');
newTweet = newTweet.replace('%','%25').replace('&','%26').replace('#','%40').replace(';','%3B').replace('?','%3F').replace('/','%2F').replace(':','%3A').replace('#','%23').replace('=','%3D').replace('+','%2B').replace('$','%24').replace(',','%2C').replace(' ','%20').replace('<','%3C').replace('>','%3E').replace('{','%7B').replace('}','%7D').replace('[','%5B').replace(']','%5D').replace('`','%60').replace('|','%7C').replace('\\','%5C').replace('^','%5E').replace('"','%22').replace('\'','%27').replace('!','%21').replace('*','%2A').replace('(','%28').replace(')','%29').replace('~','%7F');
req.setBody('status='+newTweet);
req.setHeader('Content-Type','application/x-www-form-urlencoded');
OAuth oa = new OAuth();
if(!oa.setService())
{
message=oa.message;
}
oa.sign(req);
HttpResponse res = h.send(req);
system.debug('&&&&&&&&&&&&&&&&7' + res.getBody());
PostTweetbody = res.getBody() + '___' + message;
newTweet = '';
}

Resources