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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

The command line version of ‘httparty’ with basic authentication works simple and great:

httparty -u username:password http://example.com/api/url

But now I’m looking for the way I can add the basic auth to a HTTParty.get call from within a Rails app. First of all, for testing purposes, I want to hard code the login credentials in the Controller. Just to make sure it works. But I can’t find any documentation or examples how you can pass these along.

A HTTParty.get without credentials works fine:

@blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json")

But I don’t see how I can make a variation on this that accepts the -u username:password part.

The next challenge for me (am very new to Ruby/Rails) is to get the user credentials from a user form and pass it along dynamically, but most important for me now it to get the hard coded version to work.

Answers:
auth = {:username => "test", :password => "test"}
@blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json", 
                     :basic_auth => auth)

Questions:
Answers:

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.