Getting Facebook Access Token from User Id and Facebook App Secret?

Tom Jenkinson picture Tom Jenkinson · Aug 12, 2013 · Viewed 13.6k times · Source

I'm trying to understand how the facebook api works. The end goal is to be able to read the posts from a facebook page.

If someone has connected with my app on facebook can my c# application then get the posts from a public facebook page if it knows their facebook account id (and has the facebook app secret hard coded).

If so what are the http requests it needs to make in order to get the access token which can then be used to get the posts, and what are the requests to get a new access token before one expires?

If you could provide an example in c# (maybe using the acebooksdk.net library) that would be great!

Thanks.

Answer

Tom Jenkinson picture Tom Jenkinson · Aug 13, 2013

The way to do it was using "The Login Flow for Web (without JavaScript SDK)" api to get a user access token. A user access token is required to be sent with graph api queries in order to get page posts.

The first step is to create an app on facebook where you specify what information you want the program to be able to access via the graph api. The end user will then choose to accept these permissions later.

The program creates a web browser frame and navigates to https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token

The response type "token" means that when the (embedded) web browser is redirected to the redirect_uri the user access token will be added to the end of the url as a fragment. E.g the browser would end up on the page with url https://www.facebook.com/connect/login_success.html#access_token=ACCESS_TOKEN...

The redirect uri can be anything but facebook has that specific one set aside for this scenario where you are not hosting another server which you want to receive and process the response.

Basically facebook gathers all the information required from the user and then sends them to the redirect_uri. Some information they may require is for them to login and accept permissions your app on facebook requires.

So the program simply keeps an eye on what url the embedded browser is on and when it matches the redirect_uri it parses the url which will contain the data as fragments and can then close the browser.