How to use omniauth to make authenticated calls to services?

旧街凉风 提交于 2019-12-03 13:02:17

Hey, I'm the author of the OmniAuth gem. OmniAuth is meant to be used for the authentication process. In the case of OAuth providers like Netflix, this means exchanging a request token for an access token which is then used to pull user information from the API. These one-off calls are specifically designed for each provider and are not meant to be a generic API client for the given provider.

What you can do it use OmniAuth to obtain the credentials and then use another specific library for the site itself (such as ruby-netflix or anything else, I'm not sure what the best one is) to make calls. You can retrieve the access token and secret that is obtained in the authentication dance by accessing env['omniauth.auth']['credentials'], then use those to initialize the API client.

You can also use the OAuth library directly to make these calls, but I would strongly recommend just using an existing library, it will be much faster and easier. Does all of that make sense?

OmniAuth is all about authentication; you should probably look at another gem for making actual calls to the service. E.g., for Facebook, I use the OAuth2 gem and code like the following:

module Facebook
  class Client < OAuth2::Client
    # Return a new OAuth2::Client object specific to the app.
    def initialize
      super(
        APP_CONFIG[:facebook][:api_key],
        APP_CONFIG[:facebook][:app_secret],
        :site => 'https://graph.facebook.com',
        :parse_json => true
      )
    end
  end

  class Token < OAuth2::AccessToken
    # Return a new OAuth2::AccessToken specific to the app
    # and the user with the given token.
    def initialize(token)
      super(
        Facebook::Client.new,
        token
      )
    end
  end
end

access_token = Facebook::Token.new(users_fb_token)
url          = "https://graph.facebook.com/#{user_fb_id}/feed"
response     = access_token.post(url, :message => "My update")

Note that there are gems for popular services, like Facebook and Twitter, that can manage the behind-the-scenes things like creating tokens, managing URLs, etc. For Netflix, you might check the following:

Also keep in mind that OmniAuth just returns the service data to you; you're free to store it and use it how you will (Devise has it's own pattern for OmniAuth that you might butt heads with if you try to go outside the lines). The other question you linked doesn't look too far fetched to me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!