How to use basic authentication with httparty in a Rails app?

不羁的心 提交于 2019-11-30 04:09:18
auth = {:username => "test", :password => "test"}
@blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json", 
                     :basic_auth => auth)

Two points,

  1. If you are hitting Twitter's api, unless I'm mistaken I don't think they allow basic auth anymore :( So you may want to look into something like OmniAuth for OAuth sign-in. You don't need HTTParty or a sign-in form for this, you link to the Twitter sign-in and the user enters credentials there, then Twitter sends a callback request to your app once authenticated. OmniAuth does most of the work for you, you just pull the info you need out of what it gives you in the callback route.

  2. But even so, you will still need the OAuth 'consumer key' and 'consumer secret' which are specific to your application (how Twitter authorizes your application, as distinguished from the user). And you don't want these, nor any auth keys, in your source code.

A typical way of doing this is stick them into a config/omniauth.yml file which is not checked in to source control:

twitter:
  key: CONSUMER_KEY
  secret: CONSUMER_SECRET

And then load them in an initializer config/initializers/omniauth.rb :

consumers = YAML.load("#{Rails.root}/config/omniauth.yml")

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, consumers['twitter']['key'], consumers['twitter']['secret']
end

You could take a similar approach with loading basic auth username/passwords, just stick them in some object that you'll have access to from wherever you make the HTTParty calls.

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