首页 文章

使用omniauth进行facebook登录时只使用访问令牌

提问于
浏览
8

我正在为移动应用程序创建一个用于rails的api . 现在用户将使用Facebook登录,我将收到facebook身份验证后的访问令牌 . 我必须使用此访问令牌并检查应用程序数据库中是否存在访问令牌 . 如果是,则允许用户访问,如果没有,则检查电子邮件并更新访问令牌并允许用户访问 .

我如何通过omniauth-facebook和设计实现这一点,据我所知omniauth-facebook从头开始做所有事情,找不到只提供访问令牌到omniauth-facebook的方法 .

任何帮助都会很棒 .

1 回答

  • 15

    你不需要omniauth-facebook . 此gem的目的仅是获取访问令牌(并查询用户的信息) . 以下是标准设置中的事情(使用Devise和omniauth-facebook):

    • Omniauth获取访问令牌

    • Omniauth获取用户's informations through through Facebook'的API并将其存储在请求的环境中

    • Omniauth在您需要编写的应用程序中调用自定义回调方法

    • 此回调方法在数据库中检索或创建用户,然后使用Devise提供的一些帮助程序对用户进行签名 .

    (更多细节请参见Devise's documentation about Omniauth

    现在,鉴于您已经拥有访问令牌,并且从Facebook的API获取用户的信息非常简单,您实际上并不需要omniauth-facebook .

    您需要做的就是写一个动作:

    • 接收访问令牌(作为参数)

    • 获取用户信息(图表API请求为/me

    • 在数据库中查找或创建用户(使用用户的Facebook ID)

    • 签署用户使用Devise的助手

    此代码基于Devise's documentation中给出的示例 .

    class Users::FacebookCallbacksController
      def facebook
        # You should test if params[:access_token] is present
        # and if this request fails
        facebook_data = HTTParty.get("https://graph.facebook.com/me", query: {
          access_token: params[:access_token]
        }).parsed_response
    
        # You need to implement the method below in your model (e.g. app/models/user.rb)
        @user = User.find_for_facebook_oauth(facebook_data)
    
        if @user.persisted?
          sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
          set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
        else
          session["devise.facebook_data"] = facebook_data
          redirect_to new_user_registration_url
        end
      end
    end
    

    Notes:

    • 我在这里使用HTTParty gem来调用Facebook API,但还有其他可能性,包括Koala

    • sign_in_and_redirectset_flash_messageis_navigational_format? 是Devise提供的助手

    • 有关 User.find_for_facebook_oauth 的实施,请参阅Devise's documentation

    • 一个名为devise_facebook_open_graph的宝石以略微不同的方式做同样的事情 . 它并未真正使用或维护,但您可能对实现感兴趣 .

相关问题