Auto Facebook OAuth from ASP.NET C# - c#

I need help on oAuth authentication to facebook. I am able to do the steps that facebook API mentioned and successfully authenticated, get my profile information as well as post to my news feed.
I want my application to login automatically rather than routing to Facebook login page on behalf of a user(i.e. get credentials from db and do auto oauth) . So that the user can type a message on application and click on button should submit a post to facebook page.
Thanks

What you need to get is an access token. This is a key which allows you continued access to the account until your the token expires or the user cancels it.
When you first authenticate if you have set the required permissions you get an authtoken which you can store and use to initiale further calls.
var client = new FacebookClient("my_access_token");
dynamic result = client.Get("19292868552_118464504835613");
string id = result.id;
string fromName = result.from.name;
string fromCategory = result.from.category;
string message = result.message;
int likes = result.likes;
foreach (dynamic comment in result.comments.data) {
string commentId = comment.id;
string commentMessage = comment.message;
}
see this article for details about the process:
http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/

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}

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()

C# Facebook SDK - How to use web forms to server side authorize canvas application

There are lots of sample applications in MVC but the current project I'm working on requires that I use web forms.
I can authorize the application using the javascript method but I want to use server side. Below is what I started with on the page.load
dynamic parameters = new ExpandoObject();
parameters.client_id = AppId;
parameters.client_secret = appSecret;
parameters.response_type = "code";
//parameters.state = state;
parameters.redirect_uri = "http://fb.local/page.aspx";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
//parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(ExtendedPermissions))
parameters.scope = ExtendedPermissions;
// generate the login url
var fb = new FacebookClient();
var loginUrl = fb.GetLoginUrl(parameters);
Response.Redirect(loginUrl.AbsoluteUri, true);
I can authorize but I'm not able to get the access token from the URL.
On the next page I can view source and see the access token in the url bar but I'm not sure how to go about getting it into the code. once I have the token, I'm all set.
page.aspx#access_token=AAACrxQhmdpY
I used to this code on my page load and works, its not a very clean code, but you may figure out how to change it for your best use. so the algorithm is that when the page loads you redirect the user to Facebook authentication page using response.redirect to a string that contains three parameters:your app ID(appid), what permissions you are asking your user(scope), where you want Facebook to redirect the user after authorization, and a parameter as state which i guess it should be a random number. so after the user authorized your application he/she will be redirected to your page, with a request URL that contains the same state you prepared Facebook with(and you can use to identify who which request was which if there are many requests i guess) and also a new "code" parameter which you pass on to Facebook to obtain access token, you can use Facebook c# sdk to obtain the access token.in my code there is a line that says "if code is not null, go to alireza" and alireza is a line tag after the response.redirect code, this is because you dont want the process to be repeated all over and over (and of course probably the browser show an error).
int intstate;
string strstate;
string redirecturltofb;
string scope;
string appid;
code = Request.QueryString["code"];
if (!String.IsNullOrWhiteSpace(code))
{
goto alireza;
}
appid = "424047057656831";
scope = "user_about_me,user_activities,user_groups,email,publish_stream,user_birthday";
intstate = 45;
strstate = Convert.ToString(intstate);
redirecturltofb = "https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=http://test5-2.apphb.com/&scope=" + scope + "&state=" + strstate;
Response.Redirect(redirecturltofb);
You have to use Javascript SDK to get access token back to code behind.
Use FB.Init as in http://csharpsdk.org/docs/web/getting-started
and do post back on certain conditions to get the access token.
Thank you,
Dharmendra

How to get the facebook user token with a facebook application

I have a facebook application with has to post updates on specific facebook page. The application has rights to post updates on the facebook wall of the page's admin. But how can i get the (admin's) users access token, which i need to get the access token of the page. Do i have to save the access tokenthe first time the user allows the app to post (offline access)?
Thanks for your reply!
I use the Facebook C# SDK as well. You'll need the following permissions:
manage_pages
read_stream
publish_stream
HTTP Get to "me/accounts" and get the .data object off of the returned value. This will be a list of the following:
var list = ApiGet("me/accounts").data;
foreach (dynamic acc in list)
{
var name = (string)acc.name;
var accessToken = (string)acc.access_token;
var category = (string)acc.category;
var pageId = (string)acc.id;
}
As you can see, each one of the pages have their own unique access token.

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.

Categories

Resources