错误请求尝试使用Ruby中的Digest Auth调用服务

时间:2017-02-03 15:24:31

标签: ruby-on-rails ruby web-services authentication digest-authentication

我正在尝试使用Digest Auth从rails应用程序调用服务,它总是返回400错误的请求错误。

我使用net-http-digest_auth gem来创建标题,但我想我错过了一些东西。

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

  http = Net::HTTP.new uri.host, uri.port
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  req = Net::HTTP::Get.new(uri.request_uri)

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

  digest_auth_request = Net::HTTP::DigestAuth.new

  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
  else
    error
  end

  response_body
end

请求的标题如下所示:

Digest username=\"myuser@mydomain.com\", 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\""

我无法弄清楚发生了什么,是否有其他宝石可以让这更容易?

1 个答案:

答案 0 :(得分:0)

最后通过比较浏览器标题与ruby标题找到了问题。

我没有正确计算“nc”(调用计数器)。添加+1后,它开始返回401错误(现在我有一个不同的问题;))。