im just going to dive straight in and give you a little background on what im trying to do, what i've tried, and the obstacles in my way. so here goes..
MY GOAL
To post to a facebook profile or wall from a desktop application.
The desktop application will be used by individual users who have their own facebook account.
The aim is to create each user their own facebook app and get the app id and app secret.
And then use the app id and app secret in the desktop application ( Saved somewhere in database or config )
to allow the user of the desktop application to post to their profile without having to enter their email address and password to login first
So in summary, 1 facebook app per facebook account.
The app settings will be saved in each users desktop application
Post to their own facebook via their own facebook app without logging in
The main emphasis here being that the user does not have to log in manually via a window or browser.
I have created my facebook app and have set it to live status.. i have also added in all possible permissions and extended permissions in the settings ( Within facebook ) just to make sure i wasnt missing anything.
So I do have my AppID and App secret.. I also have my Client Token which it says to use in place of the app secret for 'auth methods'. I use this to get my access token. I tried the app secret and it doesnt return the access token
MY ATTEMPTS :
C# FACEBOOK SDK
So, i started with and am still trying to use the c# sdk
I can retrieve my access token but cannot post.
I get he below errors all the time with whatever i try... these are just 2 of the many code examples i have tried.
(OAuthException - #2500) An active access token must be used to query information about the current user.
dynamic r = fb.Post("me/feed", new { message = "My seconds wall post using Facebook C# SDK" });
(OAuthException - #190) The client token cannot be used for this API
dynamic r = fb.Post("kevin.maguire.965/feed", new { message = "My second wall post using Facebook C# SDK" });
I read the following extract from the below link which states my access token is an app token and i need a access token for a user or page?
Need Help on OAuthException Code 2500
Error 2500 means you have no access token or an app access token but are trying to access /me/ - 'me' is a placeholder for 'current user or page ID' so won't be valid without an access token for a user or page
So, i have tried to get the userID back using the following Answer ( Facebook C# SDK Get Current User )
var fb = new FacebookClient("access_token");
dynamic result = fb.Get("me", new [] { fields = "id" });
var userId = result.id;
I get the access token which i assume is the app token and not the user token
dynamic result = fb.Get("oauth/access_token", new
{
client_id = this.ApplicationId,
client_secret = this.AppSecret,
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
So i have no idea at this moment in time how to post to my profile
I am able to achieve the above using twitter where i can use the secret, token, id etc ... they provide and I can successfully post to my twitter account from a desktop application WITHOUT logging into my twitter account.
Another user has also found it quite easy to post to twitter without any real issues. ( facebook c# sdk getting started )
He also seems to have had success which i have not using the same code - this code was uses in June 2012 so there could have been breaking changes released since
then.
I got the message : (OAuthException - #2500) An active access token must be used to query information about the current user... when i used the sdk.
When i tried to get the access token using a web request and then pass that token to the sdk object to create a facebookclient i got this message
(OAuthException - #190) Invalid OAuth access token signature.
WebRequest request = WebRequest.Create("https://graph.facebook.com/oauth/access_token? grant_type=client_credentials&client_id=999999999999999&client_secret=edefefr8e09r8e08r080r8er0e");
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string accesstoken = reader.ReadToEnd();
MessageBox.Show("accesstoken")
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
var fb = new FacebookClient(accesstoken);
dynamic parameters = new ExpandoObject();
parameters.message = "test";
dynamic result = fb.Post("me/feed", parameters);
var id = result.id;
Obviously in the code above i changed the id and secret to dummy values.
So basically folks...the above links and above code are only a pinch of what I have tried to date in the last few days... i've basically ran out of options and am missing something here which could be averting my attention easily.. or maybe not :) i dont know.
If any one would even have a simple windows form, or wpf window application example using the c# sdk or using restsharp or just using WebRequest object with 'POST' method then I would be eternally greatful.
Just to iterate again that it is a desktop application and not ASP.net .
Many thanks folks for your attention and time.
From what I can see you are supplying an incorrect access token. Since you haven't provided the code with regards to obtaining the access token, may I suggest you take a look at this link which explains how to build a Facebook application, including obtaining an access token via a WebBrowser control.
EDIT: You are supplying the app access token but are trying to post as a user. For this operation you need a user access token which you can obtain by following the steps in the link above.
Related
I'm implementing Dropbox access into my .NET application
I have a question about the token system by OAuth 2 from Dropbox.
The steps I followed to successfully getting data from Dropbox
ClientSecret and ClientId are given ofc
1. Authorize: by calling https://www.dropbox.com/1/oauth2/authorize
2. Verify the code by Request.QueryString("code")
3. Getting Account info with the response see below:
Getting Account info
var client = new HttpClient()
{
BaseAddress = new Uri("https://api.dropbox.com")
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync("/1/account/info");
var AccountData = JsonConvert.DeserializeObject<DropBoxAccountData>(await response.Content.ReadAsStringAsync());
//Note: DropBoxAccountData is my custom class.
// The Token is also given don't show the code just the querystring["code"]
// that dropbox return by youre redirect_uri
Everything works fine so far.
The first step every time a user access my webpage it needs to be verified by his/her Dropbox account to allow permission from my Dropbox app.
The second time it needs to be know by the application using MSSQL Database or just session for example.
But it looks like it always expires?
Please is there someone that can point me into the right direction.
Once you have the access token ("token" in your code above), you just need to save it. It sounds like you're building a web app, so yes, you would typically store this in the user's session or perhaps associated with the user in a database, if you have such a thing.
I am writing an app that will talk with Salesforce. Salesforce provides access to APIs via OAuth. I've been attempting to go through the OAuth authentication process described here. Currently, I'm attempting to authorize my app. I have the following code.
// Ask Salesforce for a request token
var request = (HttpWebRequest)(WebRequest.Create(String.Format("https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id={0}&redirect_uri=http://localhost:5004/home/AuthCallback", CONSUMER_KEY)));
request.Method = "POST";
request.ContentType = "application/json";
// Retrieve the request token from the response
var response = (HttpWebResponse)(request.GetResponse());
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string accessCodeData = accessCodeReader.ReadToEnd();
}
This code is triggered when a user clicks a button in my ASP.NET MVC view. When executed, this code calls to Salesforce. I see a request in fiddler. The request header looks like this:
POST /services/oauth2/authorize?response_type=code&client_id={consumerKey}&redirect_uri=http://localhost:5004/home/AuthCallback HTTP/1.1
I am in fact passing my consumer key, I'm just removing it from the example. Regardless, this request returns a 302, with a body size of 0. I might be misunderstanding something. However, I was expecting to get a request token. I was then going to use the request token to get the access token.
What am I doing wrong?
You are misusing the API.
Take a closer look at the sequence diagram at their page (under Obtaining an Access Token): in the auhorization_code flow you are supposed to redirect the browser to their page so that the user sees the login page, provides his/her credentials and you get the token back. Instead, you are trying to POST there using a web request from your server.
This particular flow belongs then to the passive flows group, this group is intended to be used in browser apps, your server redirects the browser to their server and you basically get the response to the uri passed in the redirect_uri parameter and this should point back to your application at your server.
There are other flows, of them one is suited for non-browser apps, it is called resource owner password flow. In this flow it is your application that hosts the login UI and you send the username/password to the authorization server and you get the token back. It is to be read in their docs however whether this flow is supported.
Read more here: http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified
Take a look how I handle the OAuth2 flow to Google, using the DotNetOpenAuth library. This is a direct solution, applying it to any other provider should be straightforward.
http://www.wiktorzychla.com/2014/11/simple-oauth2-federated-authentication.html
I need to post a message from my personal website to the website´s facebook wall page. I dont want the user to authenticate against facebook, instead a default website account should be used(probably the facebook app).
This is what I have :
Created facebook App at https://developers.facebook.com
Add Facebook.dll to my ASP.NET webform site(the personal site)
Included the following code :
FacebookClient client = new FacebookClient();
result = client.Get("oauth/access_token", new
{
client_id = ConfigurationManager.AppSettings["FacebookAppId"],
client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
grant_type = "client_credentials"
});
client.AccessToken = result.access_token;
result = client.Post("1418771281723422/feed", new { message = "Test Message from app" });
result = client.Get("1418771281723422");
This returns the following exception on client.Post
A first chance exception of type 'Facebook.FacebookOAuthException'
occurred in Facebook.dll
Additional information: (OAuthException - #200) (#200) The user hasn't
authorized the application to perform this action
What am I doing wrong and why is it so hard to do this simple task?
Of course you need to authorize a User to post on Facebook - else it would be incredibly easy to create a spam App.
What you need is a Page Access Token, take a look at the Facebook docs about the different Tokens and how to get them: https://developers.facebook.com/docs/facebook-login/access-tokens
More information about Access Tokens: http://www.devils-heaven.com/facebook-access-tokens/
The code is in PHP, but the text is valid for every language anyway.
This is how to generate an Extended Page Token with PHP: http://www.devils-heaven.com/extended-page-access-tokens-curl/
An Extended Page Token may be exactly what you need, it is valid forever and you can post "as Page" with it.
Doing this with ASP.NET should be pretty similar, but you don´t really need that Facebook SDK if you take a look at the tutorial for extending a Page Token with CURL. This question may help you: curl Request with ASP.NET
To create an Extended Page Token only for yourself, i suggest creating it without any coding:
Use the Graph API Explorer to create a User Access Token with your App.
Extend the User Access Token: https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=[app-id]&client_secret=[app-secret]&fb_exchange_token=[short-lived-token]
Put that resulting User Token in the "Access Token" field of the Graph API Explorer
Make a call to /me/accounts to get a list of all your Facebook Pages
Take the Access Token of your Page and use it in a server side call for posting
It´s explained in this article: http://www.devils-heaven.com/facebook-access-tokens/
I have developed an application to download user names and Ids from face book graph API. But I cannot get their public information like birthdays.
So my approach is to download HTML of about pages and read Birthday from that.
my code follows; I developed my application in MVC4:
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (result.ExtraData.Keys.Contains("accesstoken"))
{
Session["facebooktoken1"] = result.ExtraData["accesstoken"];
string fbToken = result.ExtraData["accesstoken"];
ViewBag.TokenToview = fbToken;
ViewBag.Id = 5;
WebRequest myWebRequest = WebRequest.Create("https://www.facebook.com/amila.u.abeyrathne/about");
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream ReceiveStream = myWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(ReceiveStream, encode);
string strResponse = readStream.ReadToEnd();
}
When I use this I only get html of LOG IN page of facebook. How can I use my facebook login session in this application?
To get information like this, you'd need to hit Facebook Graph API endpoints like mentioned here
. You'd need an access token gneerated with the necessary permissions as specified here in order to submit a working request. I'm assuming the access token you're using in this code is generated by querying OAuth in the specified manner.
It is not possible to get those information from facebook graph Search.The solution is to develop application that can log in to facebook and scrap the HTML of the facebook wall of each user whom userids have being downloaded. After scraping the HTML read the text from htlm is the solution. But it is not that much accurate. Birthdays and other information in the about page is not possible to read on that way either because there is no way to navigate to the about page in that way.
Ur application session data cannot be read by facebook API, so need to send the token in subsequent requests.
Getting FB Page data from facebook using C#
I think your approach is wrong. when you log in to a website it is created session cookie in client browser. Then it append to each request header when send request to that web site again. session cookie created on client browser not the server.
What you are doing is you send request to facebook from your server not from the client. Then there is no valid session cookie append to your request.
If you what to go this way you have to read the facebook page using javascript. But it is not the recommended way.
You need to crate facebook app for your website.
Then need to Select permissions to request from users. (for your case use user_birthday )
Then authenticate your website using that app. Then you can get what ever the details that you want using graph api if users gave permission.
I would like to write a console application that automatically posts information to my wall once every morning.
I have signed up for facebook developer and have a AppID and App Secret
I have been trying to play with the C# facebook SDK and looked through several examples.
Seems like the examples get a user token - but have to use a browser that is in windows forms. This is an automated process - so I dont want to have a user present.
Ive also created some examples using the application token - but it does not seem to be able to write to the wall.
I wrote the Twitter equivalent very quickly. I must be missing something here ???
What is the proper way to proceed?
It seems that all I should need to is:
FaceBookClient(appID, appSecret)
and then just
FaceBookClient.Put(message)
???
clarification added:
Playing with the C# facebook sdk winform application
I had to change their FacebookLoginDialog.cs to use the folling URL:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APPID&client_secret=APPSECRET&scope=user_about_me,publish_stream,offline_access
which returns an accesskey in WebBrowser.DocumentText
If I then call:
var fb = new FacebookClient(_accessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!";
dynamic result = fb.Post("me/feed", parameters);
I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
If I change the code above to NOT use that access token - but use the appID and Appsecret:
FacebookClient myFacebookClient = new FacebookClient("APPID", "APPSECRET");
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!";
dynamic result = myFacebookClient.Post("me/feed", parameters);
Then I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
I guess it is the same exception
Here is what I found.
Download the facebook C# sdk source code and samples from http://facebooksdk.codeplex.com/
Unzip the code and load into Visual Studio the Facebook C# SDK sample called CS-WinForms.
At the top of Form1.cs - enter your application ID
Run the application.
Form1.cs pops up with a button "Login to Facebook". Click the button.
FacebookLoginDialog.cs pops up with a browser window in it displaying facebook asking for permissions.
FacebookLoginDialog.cs creates a browser window that will go to your user on facebook and request permissions. By default those permissions are: user_about_me,publish_stream,offline_access.
Offline_access means the AccessToken you get - never expires
Click "OK" in Facebook to allow the application to access your facebook data.
FacebookLoginDialog.cs should find that you logged in and get the access token that never expires.
The access token is a string.
Insert a break point so that you can copy this access token. Save this access token as you can use it from now on to access to Facebook.
Facebook developers website has some tools that you can use to check the access token
https://developers.facebook.com/tools/debug/access_token
You can enter your access token and click "Debug" and it should list your applicationID, UserID, and for "expires" it should say "never".
Once you have this access token - then you can simply write code like:
var fb = new FacebookClient(AccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = FacebookString;
dynamic result = fb.Post("me/feed", parameters);
var id = result.id;
to post message to Facebook!
You should request offline_access in addition to publish_stream. Once you have the never-expiring token, store that in your app.