Can I pass the id + facebook token to the Rails Devise service for user authentication?

I have a Rails web service working with Devise + OmniAuth. I have users who authenticate Facebook Connect on a mobile device. Then I want the mobile device to establish a session with our web services. What do I need to transfer to the device from the mobile client to establish this session? Is there any sample code on the Rails side for how to handle this id + token, which is passed from facebook → mobile → web service?

+4
source share
2 answers

I have not found a good way to do this. I don't use :omniauthable , I use OmniAuth and Devise separately, as shown in the Railscast episode, where there are two users and authentications tables. This is a kind of hack and works only for Facebook.

Basically, send your access_token from iPhone to the server via SSL or something similar. You must check with OmniAuth first, and if you are granted access, you can manually create a session with OmniAuth by going something like:

I managed to work something by doing this, though:

 FB = OmniAuth::Strategies::Facebook.new("nothing") client = ::OAuth2::Client.new("nothing", "nothing", FB.client_options) cached_token = "app_id_part|session_id_part|token_part" # or maybe you sent it from the iPhone access_token = ::OAuth2::AccessToken.new(client, cached_token) FB.instance_variable_set("@access_token", access_token) FB.auth_hash # You will either get a hash or get this error: # OAuth2::AccessDenied: Received HTTP 401 during request. 

After that, you look at the user information that you need to find in your Authentication table:

 @user = Authentication.where(:uid => FB.auth_hash["uid"], :provider => "facebook").first.user 

Now we create a session:

 sign_in_and_redirect(:user, @user) # or, perhaps sign_in(@user, :bypass => true) 
+4
source

It was hard for me with this, so I will post my answer here for someone else. This inspires Dex's answer above.

 FB = OmniAuth::Strategies::Facebook.new("APP_ID", "APP_SECRET") client = OAuth2::Client.new("APP_ID", "APP_SECRET", FB.options.client_options) token = OAuth2::AccessToken.new(client,'ACCESS_TOKEN', FB.options.access_token_options) FB.access_token = token FB.auth_hash 

Any suggestions for improving this would be appreciated.

The snippet above allows me to get auth_hash by accessing facebook using access_token

I use this gem: github.com/mkdynamic/omniauth-facebook

+2
source

All Articles