具有基本身份验证的“httparty”命令行版本工作起来简单而出色:
httparty -u username:password http://example.com/api/url
但现在我正在寻找可以从 Rails 应用程序内将基本身份验证添加到 HTTParty.get 调用的方法。首先,出于测试目的,我想在控制器中对登录凭据进行硬编码。只是为了确保它有效。但我找不到任何文档或示例如何传递这些内容。
没有凭据的 HTTParty.get 工作正常:
@blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json")
但我不知道如何对此进行修改以接受 -u username:password 部分。
我(对 Ruby/Rails 非常陌生)面临的下一个挑战是从用户表单获取用户凭据并动态传递它,但现在对我来说最重要的是让硬编码版本正常工作。
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.
发布评论
评论(2)
两点,
如果你正在使用 Twitter 的 api,除非我弄错了,否则我认为他们不再允许基本身份验证:( 所以你可能想研究一下类似 OmniAuth 用于 OAuth 登录。为此,您不需要 HTTParty 或登录表单,您可以链接到 Twitter 登录,然后用户输入那里的凭证,一旦经过身份验证,Twitter 就会向您的应用程序发送回调请求,OmniAuth 会为您完成大部分工作,您只需从回调路由中为您提供的信息中提取所需的信息即可。
但即便如此,您仍然需要特定于您的应用程序的 OAuth“消费者密钥”和“消费者秘密”(Twitter 如何授权您的应用程序,以区别于用户)。并且您不希望在源代码中包含这些或任何身份验证密钥。
执行此操作的典型方法是将它们粘贴到未签入源代码管理的
config/omniauth.yml
文件中:然后将它们加载到初始化程序
中config/initializers/omniauth.rb :
您可以采用类似的方法来加载基本身份验证用户名/密码,只需将它们粘贴到某个对象中,无论您在何处进行 HTTParty 调用,都可以访问该对象。
Two points,
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.
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:And then load them in an initializer
config/initializers/omniauth.rb
: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.