views:

130

answers:

3

I've been trying to get Rails to play with the new Facebook Graph API. After I get the authorization "code", I need to send another request which returns the access token in JSON form.

It seems to work fine, however I want to fetch the access token JSON without redirecting the user. I'm attempting to use Net::HTTP.get, but I'm not sure how to use it to get a request body, or even if it's the right thing to use to begin with.

Can anyone give an example of performing an HTTP GET?

A: 

SOA#1

However please note that it means that server have to be log onto facebook - while if browser is redirecting it is user who have to be log into server. Hence did your server set the permission?

  • You can pretend that you are the user. Bad Horrible idea (you have to store passwords in cleartext on you server).
  • You can use OAuth. Hence you should use OAuth gem instead of Net::HTTP. You will not avoid the redirection - it is part of authorisation process and user must say that he allows to access data (imagine what would be if anyone could access anyone data on facebook). Turorial on writing OAuth clients in rails.
Maciej Piechotka
Graph API uses OAuth2, and while there is a gem for that, it uses Rack 1.1.0 which interferes with Rails 2.3.5's requirement of Rack 1.0.x, so I'd like to avoid that if possible.I've actually managed to get the access token via some manual requests, the problem is that in the second stage--this is after redirection to FB and back, and it sent me the "code"--the access token is just displayed as JSON when I request it, and doesn't redirect back to my app. I need to read that JSON, similar to fetching any page in general, I just need to know how to do it in Rails.
Karl
+1  A: 

I've figured out how to do this, the problem was mainly with the fact that I needed an HTTPS connection.

Adapted from http://snippets.dzone.com/posts/show/788:

path = '/oauth/access_token?...'
http = Net::HTTP.new('graph.facebook.com', 443)
http.use_ssl = true
res = http.get(path, nil)
@access_token = res.body

Anyone specifically trying to use the Graph API, note that the value stored in @access_token is in the form of a params string, e.g. "access_token=xxxx&expires=1234".

I got around needing to parse this by just redirecting to another page and using that as the URL params, but there's probably a better way to do this.

Karl
A: 

I've been looking for a way to do this for a day now. This was so simple! Thank you for your post.

Shanif