Question

I have the following class performing some requests:

  • the first request uses a digest auth
  • the second request uses a basic auth

When I run the second request I have the following error:

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

How can I invalidate the digest_auth prior to running the second request?

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
Was it helpful?

Solution

When you use basic_auth or digest_auth, HTTParty stores the information internally in the @default_options hash. Here is the source for basic_auth:

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

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

You can get access to that hash using the default_options method:

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

def default_options #:nodoc:
  @default_options
end

I'd try:

default_options.delete(:basic_auth)

or:

default_options.delete(:digest_auth)

prior to using the other authentication method.

This is untested code but looks 'bout right:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top