Class: HTTPX::Plugins::DigestAuthentication::Digest

Inherits:
Object
  • Object
show all
Defined in:
lib/httpx/plugins/digest_authentication.rb

Instance Method Summary collapse

Constructor Details

#initialize(user, password) ⇒ Digest

Returns a new instance of Digest.



69
70
71
72
73
# File 'lib/httpx/plugins/digest_authentication.rb', line 69

def initialize(user, password)
  @user = user
  @password = password
  @nonce = 0
end

Instance Method Details

#generate_header(request, response, _iis = false) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/httpx/plugins/digest_authentication.rb', line 75

def generate_header(request, response, _iis = false)
  meth = request.verb.to_s.upcase
  www = response.headers["www-authenticate"]

  # discard first token, it's Digest
  auth_info = www[/^(\w+) (.*)/, 2]

  uri = request.path

  params = Hash[auth_info.scan(/(\w+)="(.*?)"/)]

  nonce = params["nonce"]
  nc = next_nonce

  # verify qop
  qop = params["qop"]

  if params["algorithm"] =~ /(.*?)(-sess)?$/
    algorithm = case Regexp.last_match(1)
                when "MD5"    then ::Digest::MD5
                when "SHA1"   then ::Digest::SHA1
                when "SHA2"   then ::Digest::SHA2
                when "SHA256" then ::Digest::SHA256
                when "SHA384" then ::Digest::SHA384
                when "SHA512" then ::Digest::SHA512
                when "RMD160" then ::Digest::RMD160
                else raise DigestError, "unknown algorithm \"#{Regexp.last_match(1)}\""
    end
    sess = Regexp.last_match(2)
  else
    algorithm = ::Digest::MD5
  end

  if qop || sess
    cnonce = make_cnonce
    nc = format("%08x", nc)
  end

  a1 = if sess
    [algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}"),
     nonce,
     cnonce].join ":"
  else
    "#{@user}:#{params["realm"]}:#{@password}"
  end

  ha1 = algorithm.hexdigest(a1)
  ha2 = algorithm.hexdigest("#{meth}:#{uri}")
  request_digest = [ha1, nonce]
  request_digest.push(nc, cnonce, qop) if qop
  request_digest << ha2
  request_digest = request_digest.join(":")

  header = [
    %(username="#{@user}"),
    %(nonce="#{nonce}"),
    %(uri="#{uri}"),
    %(response="#{algorithm.hexdigest(request_digest)}"),
  ]
  header << %(realm="#{params["realm"]}") if params.key?("realm")
  header << %(algorithm=#{params["algorithm"]}") if params.key?("algorithm")
  header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
  header << %(cnonce="#{cnonce}") if cnonce
  header << %(nc=#{nc})
  header << %(qop=#{qop}) if qop
  header.join ", "
end