Skip to content

Instantly share code, notes, and snippets.

@gofer
Last active August 29, 2015 14:13
Show Gist options
  • Save gofer/ad5aeafe5c38be5807b5 to your computer and use it in GitHub Desktop.
Save gofer/ad5aeafe5c38be5807b5 to your computer and use it in GitHub Desktop.
class HTTP_Digest
def initialize(uri)
@uri = uri
req = Net::HTTP::Get.new(@uri.path)
res = Net::HTTP.new(@uri.host, @uri.port).start { |http|
http.request(req)
}
@digest_hash = {}
if /Digest (.+)/ =~ res['WWW-Authenticate'].to_s then
for pair in $1.split(',')
key, val = pair.strip.split('=', 2)
if /\"(.+)\"/ =~ val then
val = $1
end
@digest_hash[key] = val
end
end
@nc = 1
end
def build_auth_header(method)
cnonce = SecureRandom.hex(8)
response_digest_hash = {}
response_digest_hash['username'] = '"' + @uri.user + '"'
response_digest_hash['realm'] = '"' + @digest_hash['realm'] + '"'
response_digest_hash['nonce'] = '"' + @digest_hash['nonce'] + '"'
response_digest_hash['uri'] = '"' + @uri.path + '"'
response_digest_hash['algorithm'] = @digest_hash['algorithm']
response_digest_hash['qop'] = @digest_hash['qop']
response_digest_hash['nc'] = sprintf('%08u', @nc)
response_digest_hash['cnonce'] = '"' + cnonce + '"'
a1 = @uri.user + ':' + @digest_hash['realm'] + ':' + @uri.password
a2 = method + ':' + @uri.path
response = Digest::MD5.hexdigest(a1) \
+ ':' + @digest_hash['nonce'] \
+ ':' + response_digest_hash['nc'] \
+ ':' + cnonce \
+ ':' + @digest_hash['qop'] \
+ ':' + Digest::MD5.hexdigest(a2)
response_digest_hash['response'] = '"' + Digest::MD5.hexdigest(response) + '"'
authorization_header = ''
for k, v in response_digest_hash
authorization_header += k + '=' + v + ', '
end
if /(.+), $/ =~ authorization_header then
authorization_header = $1
end
return 'Digest ' + authorization_header
end
end
def do_auth()
uri = URI.parse('http://mydomain/file/to/path/post.cgi')
uri.user = 'username'
uri.password = 'password'
authorization_header = HTTP_Digest.new(uri).build_auth_header('POST')
p authorization_header
req = Net::HTTP::Post.new(uri.path, {'Authorization' => authorization_header})
req.set_form_data({'name' => 'taro tanaka', 'sex' => 'male'})
res = Net::HTTP.new(uri.host, uri.port).start { |http|
http.request(req)
}
puts res.code + ' ' + res.message
puts res.body
return self
end
if self.to_s == 'main' then
do_auth()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment