使用基本身份验证访问API时,获取机械化:: UnauthorizedError:401 => Net :: HTTPUnauthorized

时间:2019-03-13 14:25:14

标签: mechanize mechanize-ruby

我正在尝试使用基本身份验证访问API。它适用于HTTParty,但不适用于2.7.6 Mechanize。

这是我尝试过的:

agent = Mechanize.new
agent.log = Logger.new(STDERR)
agent.add_auth("https://website.net/listingapi", "user", "pass")
page = agent.get("https://website.net/listingapi")

这就是我得到的:

 INFO -- : Net::HTTP::Get: /listingapi
DEBUG -- : request-header: accept-encoding => gzip,deflate,identity
DEBUG -- : request-header: accept => */*
DEBUG -- : request-header: user-agent => Mechanize/2.7.6 Ruby/2.5.3p105 (http://github.com/sparklemotion/mechanize/)
DEBUG -- : request-header: accept-charset => ISO-8859-1,utf-8;q=0.7,*;q=0.7
DEBUG -- : request-header: accept-language => en-us,en;q=0.5
DEBUG -- : request-header: host => website.net
 INFO -- : status: Net::HTTPUnauthorized 1.1 401 Unauthorized
DEBUG -- : response-header: content-type => application/json; charset=utf-8
DEBUG -- : response-header: www-authenticate => Bearer, Basic realm=ListingApi
DEBUG -- : response-header: date => Wed, 13 Mar 2019 14:14:51 GMT
DEBUG -- : response-header: content-length => 61
DEBUG -- : response-header: x-xss-protection => 1; mode=block
DEBUG -- : response-header: strict-transport-security => max-age=31536000
DEBUG -- : response-header: x-content-type-options => nosniff
DEBUG -- : Read 61 bytes (61 total)
Mechanize::UnauthorizedError: 401 => Net::HTTPUnauthorized for https://website.net/listingapi/ -- no credentials found, provide some with #add_auth -- available realms: 
from /Users/nk/.rvm/gems/ruby-2.5.3@mygems/gems/mechanize-2.7.6/lib/mechanize/http/agent.rb:749:in `response_authenticate'

我做错了什么,或者API响应出了什么问题?

PS。我发现了这一点,我认为这可能与以下内容有关:https://github.com/sparklemotion/mechanize/pull/442

1 个答案:

答案 0 :(得分:2)

使用基本身份验证时,用户名和密码会结合在一起,然后使用base64进行编码。使用Basic

将编码后的结果字符串发送到Authorization标头中的服务器

如果您使用add_auth时遇到问题,现在可以采取的解决方法是自己传递Authorization标头:

username = 'Radu'
password = 'mypassword'
agent = Mechanize.new do |agent|
  agent.pre_connect_hooks << lambda { |agent, request| request["Authorization"] = "Basic #{Base64.strict_encode64(username + ':' + password)}" }
end
page = agent.get("https://website.net/listingapi")

编辑1

现在,我再次阅读日志,可以看到www-authenticate标头显示Bearer, Basic realm=ListingApi。相反,它应该说Basic realm=ListingApi

问题是response_authenticate最不可能找到任何挑战,因为您请求的API不遵守RFC7235的这一挑战部分。

this line

之后,失踪的挑战加注401
[1] pry(main)> authenticate_parser  = Mechanize::HTTP::WWWAuthenticateParser.new
=> #<Mechanize::HTTP::WWWAuthenticateParser:0x00007fe2a5c74ec8 @scanner=nil>

[2] pry(main)> authenticate_parser.parse "Basic realm=ListingApi"
=> [#<struct Mechanize::HTTP::AuthChallenge scheme=nil, params=nil, raw=nil>]

[3] pry(main)> authenticate_parser.parse "Bearer, Basic realm=ListingApi"
=> []

编辑2

HTTParty起作用的原因是它们将Authorization header upfront直接添加到Net :: HTTP :: Get。 Mechanize利用整个挑战响应授权,并且只有在挑战方案为Basic时,他们才会添加授权。