验证 Facebook + Twitter + Instagram 的访问令牌

Validate acess token of Facebook + Twitter + Instagram

在我的应用程序中,用户可以登录或注册 Facebook、Twitter 或 Instagram。获取和验证访问令牌在应用程序中完成(Android 和 iOS)。现在,当他们发送注册请求时,我需要验证访问令牌。我是否必须手动验证每个访问令牌,如:

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)

对于 Facebook,我会推荐考拉:https://github.com/arsduo/koala

推特:https://github.com/sferik/twitter

对于 Instagram,这是官方图书馆:https://github.com/Instagram/instagram-ruby-gem

我必须编写自定义方法,(以防万一有人需要它):

  # Validates fb token
  def self.validate_facebook_token token
    status = false
    begin
      @graph = Koala::Facebook::API.new(token)
      status = true if @graph.get_object("me")
    ensure
      return status
    end
  end

  # Validates fb twitter
  def self.validate_twitter_token token, secret
    status = false
    client = TwitterOAuth::Client.new(
      consumer_key: APP_CONFIG["TWITTER_CUSTOMER_KEY"],
      consumer_secret: APP_CONFIG["TWITTER_CUSTOMER_SECRET"],
      token: token,
      secret: secret
    )
    status = true if client.authorized?
    return status
  end

  # validates instagram token
  def self.validate_instagram_token token, provider_id
    status = false
    instagram_reponse = HTTParty.get("#{APP_CONFIG['INSTAGRAM_URL']}/users/#{provider_id}", query: {
      access_token: token
    }).parsed_response
    status = true if instagram_reponse['meta'].present? && instagram_reponse['meta']['code'] == 200
    return status
  end

使用的宝石:

gem 'koala'
gem 'twitter_oauth'
gem 'httparty'

如果你有更好的,请告诉我。