zapico zapico - 4 years ago 108
Ruby Question

Bad Request trying to call service with Digest Auth from ruby

I'm trying to call a service with Digest Auth from a rails application and it always returns a 400 bad request error.

I've used net-http-digest_auth gem to create the headers but I think I've missed something.

def get_digest(url)
uri = URI.parse(url)

http =, uri.port
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER

req =

# Fist call with the 401 and auth headers
digest_response = http.request(req)

digest_auth_request =

uri.user = digest_auth[:user]
uri.password = digest_auth[:password]

auth = digest_auth_request.auth_header uri, digest_response['www-authenticate'], 'GET', true

req.add_field 'Authorization', auth

response = http.request(req)
# Response is always #<Net::HTTPBadRequest 400 Bad Request readbody=true>

if response.code.to_i == 200
response_body = response.body


The request's headers look like this:

Digest username=\"\", realm=\"Digest\", algorithm=MD5-sess, qop=\"auth\", uri=\"/path/WS/my%20user/path/path/path/path/service.svc\", nonce=\"+Upgraded+v1e3f88bce1c32bd15avn421e440ca6622ebadd4522f7ed201fab1421c39d8fd15b771b972c9eb59894f8879307b9e6a5544476bc05cc7885a\", nc=00000000, cnonce=\"d42e6ea8a37aadsasdbea1231232456709\", response=\"7fbfc75cc3aasdasd342230ebf57ac37df\""

I can't figure out what's happening, is there any other gem to make this easier?

Answer Source

Finally found the problem by comparing browser header vs ruby header.

I wasn't calculating "nc" (calls counter) correctly. After adding +1 it started to return a 401 error (now I have a different problem ;)).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download