RUBY - SSL, Basic Auth, and POST

假如想象 提交于 2019-12-23 08:27:51

问题


I'm having quite a hard time with this -- seems like there are a few snippets of code lying around that I can't seem to piece together. I'm simply trying to POST key/value pairs, but getting Connection refused - connect(2) (Errno::ECONNREFUSED). Help!

require 'net/http'
require 'net/https'
require 'uri'

@http = Net::HTTP.new('https://my.url.com/path', 443)
@http.use_ssl = true
@http.start() { |http|
    req = Net::HTTP.post_form(
        URI.parse('https:///my.url.com/path'),
        {'key1' => 'value1', 'key2' => 'value2'}
    )
    req.basic_auth 'username', 'password'
    response = http.request(req)
    puts response.body      
}

回答1:


HTTP#post_form will execute directly, ignoring your other settings. Try this instead:

require 'net/http'
require 'uri'

url = URI.parse('https://my.url.com/path')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'user', 'pass'
req.use_ssl = true
req.form_data({'key1' => 'val1', 'key2' => 'val2'})

resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
puts resp

You are likely to run into trouble with the server's certificates. See my other post for instructions on how to get/configure them.




回答2:


Found this question during my search for a solultion, and just to be clear emboss' code as is is non functional. What I got working is this (inside of a larger Sinatra application):

require 'net/http'
require 'net/https'
require 'uri'

set :api_username, 'usr'
set :api_passwor, 'pswd'

def do_auth_check params
    puts params.inspect

    url = URI.parse("https://my_auth_site.com:443/authenticate")
    req = Net::HTTP::Post.new(url.path)
    req.basic_auth options.api_username, options.api_password
    req.set_form_data({'username' => params[:name], 'password' => params[:pass]})

    sock = Net::HTTP.new(url.host, url.port)
    sock.use_ssl = true
    res = sock.start {|http| http.request(req) }

    # you're on your own down here to identify success/failure, but for me 2xx/3xx was ok and 401/404/500/etc would be failure
    return true if res.code.to_i < 400
    return "Error logging in"
end


来源:https://stackoverflow.com/questions/6902910/ruby-ssl-basic-auth-and-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!