如何在同一个类中使用HTTParty的Digest和Basic身份验证?

时间:2013-05-24 15:14:07

标签: ruby httparty

我有以下课程执行一些请求:

  • 第一个请求使用摘要身份验证
  • 第二个请求使用基本身份验证

当我运行第二个请求时,出现以下错误:

only one authentication method, :basic_auth or :digest_auth may be used at a time

如何在运行第二个请求之前使digest_auth无效?

class Test
  include HTTParty
  debug_output $stdout
  digest_auth 'login', 'pass'

  def first_request(href)
    self.class.base_uri "SERVER:PORT"
    response = self.class.get(href, {:query => {}})
    response
  end

  def second_request(href)
    auth = {:username => "USERNAME", :password => "PASSWORD"}
    options = { :body => xml_string, :basic_auth => auth }
    response = self.class.post('', options)
    response
  end
end

1 个答案:

答案 0 :(得分:3)

当您使用basic_authdigest_auth时,HTTParty会在内部将信息存储在@default_options哈希中。以下是basic_auth的来源:

# File 'lib/httparty.rb', line 102

def basic_auth(u, p)
  default_options[:basic_auth] = {:username => u, :password => p}
end

您可以使用default_options方法访问该哈希:

# File 'lib/httparty.rb', line 452

def default_options #:nodoc:
  @default_options
end

我试试:

default_options.delete(:basic_auth)

或:

default_options.delete(:digest_auth)

在使用其他身份验证方法之前。

这是未经测试的代码,但看起来还不错:

class Test
  include HTTParty
  debug_output $stdout

  def first_request(href)
    klass = self.class
    klass.base_uri "SERVER:PORT"
    klass.default_options.delete(:basic_auth)
    klass.digest_auth 'login', 'pass'
    klass.get(href, {:query => {}})
  end

  def second_request(href)
    klass = self.class
    klass.default_options.delete(:digest_auth)
    klass.post(
      '',
      {
        :body => xml_string,
        :basic_auth => {
          :username => "USERNAME",
          :password => "PASSWORD"
        }
      }
    )
  end
end