使用基本身份验证密钥设置http标头

时间:2013-01-17 09:25:05

标签: ruby-on-rails ruby

我有一个使用http基本身份验证保护的站点。

我希望编写一个ruby代码段,允许我传递http基本身份验证并阅读网页内容。

我在java中使用了一种方法来发送HTTP头中设置的密钥和其他细节,从而读取网页的内容。但是无法在红宝石中找到相同的东西。

编辑:

我使用的代码在这里:

   def express
    http_basic_authenticate_with :name => "dhh", :password => "secret"
   end

给了我错误:

undefined method `http_basic_authenticate_with' for #<ServiceController:0x7f9bd73e5448>

提前致谢。

3 个答案:

答案 0 :(得分:2)

设计确实内置了HTTP Basic Authentication,但您确实需要在应用中添加两件小东西才能让它正常运行:

您的用户/帐户模型中的

:database_authenticatable策略     设计初始值设定项中的config.http_authenticatable = true

Devise依赖于Warden,这是一个用于身份验证的机架框架。 Warden本身试图通过名为failure_app的东西提供对所有未经身份验证的请求的自定义响应,这是一个有效的机架应用程序。

执行http身份验证的简单代码如下:

def http_authenticate
  authenticate_or_request_with_http_digest do |user_name, password|
    user_name == "foo" && password == "bar"
  end
  warden.custom_failure! if performed?
end

还有一篇好文章。检查here

另一个解决方案(替代方案)是使用Mechanize library

    require 'rubygems'
    require 'mechanize'
    require 'logger'

    agent = WWW::Mechanize.new { |a| a.log = Logger.new("mech.log") }
    agent.user_agent_alias = 'Windows Mozilla'
    agent.auth('username', 'password')
    agent.get('http://example.com') do |page|
      puts page.title
    end

答案 1 :(得分:1)

我认为it is你在寻找什么:

 class SecretController < ApplicationController
   http_basic_authenticate_with :name => "frodo", :password => "thering"
   def index
     ...
   end
 end

您还可以为任何特定action传递例外:

 http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index

还有一个RailsCasts

编辑 - 如果你的版本的rails在3.1之前,你可以创建自己的方法:

class ApplicationController < ActionController::Base
USER, PASSWORD = 'dhh', 'secret'

before_filter :authentication_check, :except => :index

...

 private
  def authentication_check
   authenticate_or_request_with_http_basic do |user, password|
    user == USER && password == PASSWORD
   end
  end
end 

答案 2 :(得分:1)

使用httparty之类的gem:

opt = {basic_auth: {username: "user123", password: "pass"}}
response = HTTParty.get("your_site", opt)
相关问题