1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00
httparty/lib/net_digest_auth.rb
Brian Artiaco fd19af35ac Added Digest Access Authentication support to HTTParty.
New File: lib/net_http_digest.rb
From: http://codesnippets.joyent.com/posts/show/1075
This extends Net::HTTP with a new digest_authentication method.

Extended HTTParty to use this new functionality in a backwards compatible
fashion.  To use the new digest_auth method, merely use :digest_auth as your
HTTParty credentials option instead of :basic_auth.  HTTParty will take care
of the rest.
2010-05-08 00:43:53 -04:00

44 lines
1.3 KiB
Ruby

require 'digest/md5'
require 'net/http'
module Net
module HTTPHeader
@@nonce_count = -1
CNONCE = Digest::MD5.new.update("%x" % (Time.now.to_i + rand(65535))).hexdigest
def digest_auth(user, password, response)
# based on http://segment7.net/projects/ruby/snippets/digest_auth.rb
@@nonce_count += 1
response['www-authenticate'] =~ /^(\w+) (.*)/
params = {}
$2.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 }
a_1 = "#{user}:#{params['realm']}:#{password}"
a_2 = "#{@method}:#{@path}"
request_digest = ''
request_digest << Digest::MD5.new.update(a_1).hexdigest
request_digest << ':' << params['nonce']
request_digest << ':' << ('%08x' % @@nonce_count)
request_digest << ':' << CNONCE
request_digest << ':' << params['qop']
request_digest << ':' << Digest::MD5.new.update(a_2).hexdigest
header = []
header << "Digest username=\"#{user}\""
header << "realm=\"#{params['realm']}\""
header << "qop=#{params['qop']}"
header << "algorithm=MD5"
header << "uri=\"#{@path}\""
header << "nonce=\"#{params['nonce']}\""
header << "nc=#{'%08x' % @@nonce_count}"
header << "cnonce=\"#{CNONCE}\""
header << "response=\"#{Digest::MD5.new.update(request_digest).hexdigest}\""
@header['Authorization'] = header
end
end
end