看了很多之后,我发现了一些似乎有效但不适合我的解决方案...
例如,我有这个脚本:
require 'net/http'
require "net/https"
@http=Net::HTTP.new('www.xxxxxxx.net', 443)
@http.use_ssl = true
@http.verify_mode = OpenSSL::SSL::VERIFY_NONE
@http.start() {|http|
req = Net::HTTP::Get.new('/gb/PastSetupsXLS.asp?SR=31,6')
req.basic_auth 'my_user', 'my_password'
response = http.request(req)
print response.body
}
当我运行它时,它会给我一个请求身份验证的页面,但是如果我在浏览器中写入以下 URL,我可以毫无问题地进入该网站:
https://my_user:my_password@www.xxxxxxx.net/gb/PastSetupsXLS.asp?SR=31,6
我也尝试过使用 open-uri:
module OpenSSL
module SSL
remove_const :VERIFY_PEER
end
end
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
def download(full_url, to_here)
writeOut = open(to_here, "wb")
writeOut.write(open(full_url, :http_basic_authentication=>["my_user", "my_password"]).read)
writeOut.close
end
download('https://www.xxxxxxx.net/gb/PastSetupsXLS.asp?SR=31,6', "target_file.html")
但结果是一样的,网站要求用户认证。 关于我做错了什么的任何提示?我必须在 Base 64 中对密码进行编码吗?
最佳答案
我根据 Net::HTTP docs 中给出的示例编写了一段代码并在我的本地 WAMP 服务器上对其进行了测试 - 它工作正常。这是我拥有的:
require 'net/http'
require 'openssl'
uri = URI('https://localhost/')
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https',
:verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
request = Net::HTTP::Get.new uri.request_uri
request.basic_auth 'matt', 'secret'
response = http.request request # Net::HTTPResponse object
puts response
puts response.body
end
我的 .htaccess
文件如下所示:
AuthName "Authorization required"
AuthUserFile c:/wamp/www/ssl/.htpasswd
AuthType basic
Require valid-user
我的 .htpasswd
只是用 htpasswd -c .htpasswd matt
为密码“secret”生成的一行。当我运行我的代码时,我得到“200 OK”和 index.html 的内容。如果我删除 request.basic_auth
行,我会收到 401 错误。
更新:
正如@stereoscott 在评论中指出的那样,我在示例中使用的:verify_mode
值(OpenSSL::SSL::VERIFY_NONE
)对于生产而言是不安全的。
OpenSSL::SSL::SSLContext 中列出的所有可用选项文档是:VERIFY_NONE、VERIFY_PEER、VERIFY_CLIENT_ONCE、VERIFY_FAIL_IF_NO_PEER_CERT,其中(根据 OpenSSL docs )只有前两个用于客户端模式。
因此 VERIFY_PEER
应该在生产中使用,is the default顺便说一句,所以你可以完全跳过它。
关于ruby - 如何在 Ruby 中通过 HTTPs 进行基本身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13822555/