Saving Tweetinvi credentials without re-authenticating every time - c#

Basically what I'm trying to do is to get recent tweets from a user and do stuff with them. I'm using Tweetinvi with PIN-based authentication, as described on the website, like this:
// Create a new set of credentials for the application
var appCredentials = new TwitterCredentials("CONSUMER_KEY", "CONSUMER_SECRET");
// Go to the URL so that Twitter authenticates the user and gives him a PIN code
var url = CredentialsCreator.GetAuthorizationURL(appCredentials);
// This line is an example, on how to make the user go on the URL
Process.Start(url);
// Ask the user to enter the pin code given by Twitter
var pinCode = Console.ReadLine();
// With this pin code it is now possible to get the credentials back from Twitter
var userCredentials = CredentialsCreator.GetCredentialsFromVerifierCode(pinCode, appCredentials);
// Use the user credentials in your application
Auth.SetCredentials(userCredentials);
Now the problem is that I have to sign in and connect to Twitter every time I launch my application via browser, which is mildly annoying. I've tried to save my authentication details in a text file (Consumer Key, Consumer Secret, Access Token, Access Token Secret), and then just insert the info into appCredentials and userCredentials, but with no results, as I keep getting TwitterNullCredentialsException. So how do I save my credentials so that I don't have to reconnect on every launch?

I am the main developer of Tweetinvi.
If you store the 4 credentials information you can then reuse them with 2 different solutions :
Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
// OR
var creds = new TwitterCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET");
Auth.SetCredentials(creds);
The documentation might help you set up your application : https://github.com/linvi/tweetinvi/wiki/Introduction

Related

Facebook Posting Photo using App Access Token

Scenario:
User has completed the OAuth process and has given our app publish_actions, publish_stream, user_friends, and user_photos permissions.
While we have the user token from the user logging in, we have retrieved and persisted the user's Facebook id
Also while we have the user token, we have created a photo album to later post photos to and persisted the Facebook album id
NOTE: We have not persisted the user token for legacy reasons
At a later time, we attempt to post a photo to the album previously created using the following code:
FacebookClient client = null;
Dictionary<string, object> parameters = null;
string path;
FacebookMediaObject media = null;
client = new FacebookClient();
client.AppId = "{our app id}";
client.AppSecret = "{our app secret}";
media = new FacebookMediaObject();
media.ContentType = "image/jpg";
media.FileName = "AnyAllContactTypesProblem.jpg";
media.SetValue(File.ReadAllBytes(Server.MapPath(".") + "\\" + media.FileName));
parameters = new Dictionary<string,object>();
parameters.Add("name",
"Test Image 1");
parameters.Add("source",
media);
path = "/" + "{album id}" + "/photos";
dynamic result = client.Post(path,
parameters);
The POST operation results in the following exception:
(OAuthException - #102) A user access token is required to request this resource.
The Facebook documentation indicates that an "app token" which is derived from the app id and app secret can be used as the access token for posting a photo on someone's behalf as long as publish_stream permission has been provided to the app which it has in our case.
Are we missing something needed in the code above or has Facebook changed the required permissions for posting photos?
Thanks in advance.
I don't know from where did you read this-
an "app token" which is derived from the app id and app secret can be used as the access token for posting a photo on someone's behalf as long as publish_stream permission has been provided to the app which it has in our case.
But this is not true. Once you got the publish permission, you can post the stories/feeds on the wall and get the basic info using the app access token. Posting the photos is not allowed! Here's what the documentation says-
App access tokens can also be used to publish content to Facebook on behalf of a person who has granted an open graph publishing permission to your application. Reference
One thing that you can do-
Save the extended token to your server (that expires in 60-days, after that user must go through the login again to get the new token), to get the extended token-
GET /oauth/access_token?
grant_type=fb_exchange_token&
client_id={app-id}&
client_secret={app-secret}&
fb_exchange_token={short-lived-token}

Evernote AuthToken via OAuth

I have worked with OAuth before (working with Twitter and PHP) and it was simple. I am trying to get OAuth to work with the EverNote API sample https://github.com/evernote/evernote-sdk-csharp (because, as they say, "Real applications authenticate with Evernote using OAuth"). I looked at these:
Simple C# Evernote API OAuth example or guide?
https://github.com/sethhitch/csharp-oauth-sample
http://blog.stevienova.com/2008/04/19/oauth-getting-started-with-oauth-in-c-net/
But, I still don't know how to do this... This is my code:
// Real applications authenticate with Evernote using OAuth, but for the
// purpose of exploring the API, you can get a developer token that allows
// you to access your own Evernote account. To get a developer token, visit
// https://sandbox.evernote.com/api/DeveloperToken.action
String authToken = "myAuthCode";
if (authToken == "your developer token") {
Console.WriteLine("Please fill in your developer token");
Console.WriteLine("To get a developer token, visit https://sandbox.evernote.com/api/DeveloperToken.action");
return;
}
How can I add OAuth to this to get my authToken?
Thank you.
Check this sample project : http://discussion.evernote.com/topic/30584-here-is-a-net-oauth-assembly/ . I think this will help you to understand how oauth works.
For anyone trying to get this to work in MVC, I was playing around with Evernote, OpenAuth and C# this morning and managed to get it all working. I have put together a blog post / library explaining the experience and outlining how to do it with MVC here - http://www.shaunmccarthy.com/evernote-oauth-csharp/ - it uses the AsyncOAuth library: https://github.com/neuecc/AsyncOAuth
I wrote a wrapper around AsyncOAuth that you might find useful here: https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
One prickly thing to be aware of - the Evernote Endpoints (/oauth and /OAuth.action) are case sensitive
// Download the library from https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
// Configure the Authorizer with the URL of the Evernote service,
// your key, and your secret.
var EvernoteAuthorizer = new EvernoteAuthorizer(
"https://sandbox.evernote.com",
"slyrp-1234", // Not my real id / secret :)
"7acafe123456badb123");
// First of all, get a request token from Evernote - this causes a
// webrequest from your server to Evernote.
// The callBackUrl is the URL you want the user to return to once
// they validate the app
var requestToken = EvernoteAuthorizer.GetRequestToken(callBackUrl);
// Persist this token, as we are going to redirect the user to
// Evernote to Authorize this app
Session["RequestToken"] = requestToken;
// Generate the Evernote URL that we will redirect the user to in
// order to
var callForwardUrl = EvernoteAuthorizer.BuildAuthorizeUrl(requestToken);
// Redirect the user (e.g. MVC)
return Redirect(callForwardUrl);
// ... Once the user authroizes the app, they get redirected to callBackUrl
// where we parse the request parameter oauth_validator and finally get
// our credentials
// null = they didn't authorize us
var credentials = EvernoteAuthorizer.ParseAccessToken(
Request.QueryString["oauth_verifier"],
Session["RequestToken"] as RequestToken);
// Example of how to use the credential with Evernote SDK
var noteStoreUrl = EvernoteCredentials.NotebookUrl;
var noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
var noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
var noteStore = new NoteStore.Client(noteStoreProtocol);
List<Notebook> notebooks = client.listNotebooks(EvernoteCredentials.AuthToken);
You can also try the OAuth library found here : https://code.google.com/p/devdefined-tools/wiki/OAuth and follow the steps mentioned here.
The simple code to add is:
EvernoteOAuth oauth = new EvernoteOAuth(EvernoteOAuth.HostService.Sandbox, myConsumerKey, myConsumerSecret);
string errResponse = oauth.Authorize();
if (errResponse.Length == 0)
{
Console.WriteLine(string.Format("Token: {0}\r\n\r\nExpires: {1}\r\n\r\nNoteStoreUrl: {2}\r\n\r\nUserId: {3}\r\n\r\nWebApiUrlPrefix: {4}", oauth.Token, oauth.Expires, oauth.NoteStoreUrl, oauth.UserId, oauth.WebApiUrlPrefix));
}
else
{
Console.WriteLine("A problem has occurred in attempting to authorize the use of your Evernote account: " + errResponse);
}
You will need to use this assembly:
using EvernoteOAuthNet;
Available here:
http://www32.zippyshare.com/v/98249023/file.html

dropnet api c# unauthorized user exception

I am using dropnet api to access dropbox using c#.i send my apikey and secret key,i get token in response.but when i try to get account info or delete a file it throws unauthorized use exceptions.can any one help me.my code is as follow.
DropNet.DropNetClient client = new DropNet.DropNetClient("xxxxxxxxx", "xxxxxxxxx");
DropNet.Models.UserLogin login = client.GetToken();
client.UserLogin = login;
string st=client.BuildAuthorizeUrl(client.UserLogin,null);
client.Delete("/Public/testsk");
var accountInfo = client.AccountInfo();
Regards,
Shah Khalid.
Dropbox API uses standard http error codes,
in your case, 401 usually means that user access token expired or revoked and it should recreated,
All you need to do is re-authenticate end user dropbox account by doing next steps in this order:
your application basic authentication:
client = new DropNetClient(Settings.Default.DropboxApiKey, Settings.Default.DropboxApiSecret);
client.GetToken();
Let user login Dropbox with their account and approve your Dropbox app:
string url = Client.BuildAuthorizeUrl();
Retrieve and save authenticated user token:
UserLogin accessToken = Client.GetAccessToken();
Account.Token = accessToken.Token;
Account.Secret = accessToken.Secret;
Account.Status = AccountStatus.Active;
last - save account data in your app - Account.Save()

Show photos from my facebook page on my web site

I have some doubts:
I want to show the photos from my company facebook page on my company web site using C# SDK.
How can I do that with an access token which never expires? Or why my app id and app secret is not enough?
var fb = new FacebookWebClient("app_id", "app_secret");
If I only use this it says:
An active access token must be used to query information about the current user.
Basically I see non-sense to ask for a valid access token because it's not about to interact with any of my visitors' page but just simply show my photos from my company facebook page to them.
UPDATE: To get my app token I am doing:
var oauthClient = new FacebookOAuthClient
{
AppId = "app_id",
AppSecret = "app_secret"
};
dynamic result = oauthClient.GetApplicationAccessToken();
accessToken = result.access_token;
But now, how I can show photos from my account?
If I do it like:
var fb = new FacebookWebClient(accessToken);
//Get the album data
dynamic albums = fb.Get("app_id/albums");
I receive an empty JSON but I am sure that my account on facebook has several albums.
Tokens can and do expire. You must have code in place to handle when it does.
Your appid and app secret are not enough because at least one of the page admins MUST grant access to the page to get photo data via the Graph API.
Remember, the API is not only Facebook's sandbox, but they also are the ones who built it, so you're going to have to play by their rules.

Facebook access token only valid for user that created the facebook application

I have some JavaScript that logs in a Facebook user and saves the access token to a database:
window.fbAsyncInit = function () {
FB.init({
appId: '<%=FaceBookApplicationId() %>',
status: false, // check login status
cookie: true,
oauth: true
});
};
function facebookLogin() {
FB.login(function(response) {
if (response.authResponse) {
__doPostBack('__Page', 'FacebookDeliveryButton: ' + JSON.stringify(response.authResponse));
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'offline_access,read_stream,publish_stream,user_photos' });
}
A button click fires facebookLogin() which logs in a facebook user, getting a facebook session that includes an access token, which I JSON serialize and post to the server. The server then saves this access token to the database table FacebookDeliveryQueue.
I have a Windows service running that periodically queries the FacebookDeliveryQueue table and attempts to post on a user's wall using the access token we saved earlier:
IQueryable<FacebookDeliveryQueue> toSend = objectContext.FacebookDeliveryQueues.Where(p => !p.IsDelivered);
foreach (FacebookDeliveryQueue facebookDeliveryQueueItem in toSend)
{
string facebookAccessToken = facebookDeliveryQueueItem.Cart.FacebookAccessToken;
string facebookRecipientId = facebookDeliveryQueueItem.Cart.FacebookRecipientId;
var client = new FacebookClient(facebookAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = facebookDeliveryQueueItem.Cart.CustomMessageBody;
client.Post(facebookRecipientId + "/feed", parameters);
}
My problem is, this ONLY works with access tokens from the user that created the facebook application. E.g.
Success:
I, the creator of this application, log in and pick one of my friends to send a message to, this info is saved to the database, the service runs, my message is posted to my friend's wall.
Failure:
I log in on my dummy test account (approving the app permissions on this account), pick one of my dummy test account's friend, this info is saved to the database, the service runs and throws an invalid access token error.
Any ideas why?
Update: Switched to Oauth login -- no change. Still getting "(OAuthException) Invalid access token signature." when attempting to post to friend's wall.
Looks like you're using facebook's old login methods, which they recently just turned off, so your old access tokens aren't valid anymore? And your javascript isn't generating the right kind of token. Read the latest version of the FB.login documentation for more info on what changes you need to make. Specifically,
pass oauth: true to the FB.init call
check for response.authResponse instead of response.session now.
Also, check that your app isn't in "sandbox mode". Go to the app settings page and click on "advanced". Sandbox mode makes it so that only developers can use the app.
The persistence to the database was silently trimming the access token to 75 characters, which in the case of my own user, was enough (small user id because it's an old account) -- but five characters too short in the case of my test account which has a very large user id.
Woops.

Categories

Resources