SOAP request in ruby with authentication/credentials - ruby-on-rails

I am trying to send XML/SOAP data to a server using an http POST request, and am starting by converting a working Perl script to Ruby on Rails. Using some resources, I have written some preliminary code, but I am unsure how to add user authentication (running this code causes a connection timeout error).
My code so far:
http = Net::HTTP.new(' [host] ', [port])
path = '/rest/of/the/path'
data = [ XML SOAP string ]
headers = {
'Content-Type' => 'application/atom+xml',
'Host' => ' [host] '
}
resp, data = http.post(path, data, headers)
Adding http.basic_auth 'user', 'pass' gave me a no method error
Perl code for supplying credentials:
my $ua = new LWP::UserAgent(keep_alive=>1);
$ua->credentials($netloc, '', "$user", "$pwd");
...
my $request = POST ($url, Content_Type=> 'application/atom+xml', Content=> $soap_req);
my $response = $ua->request($request);
the server uses NTLM, so maybe there is a gem you could recommend (like this?). It looks like the Perl script is using user agents, so I would like to do something similar in Ruby. In summary, how do I add user authentication to my request?

Have you looked at savon gem, https://github.com/savonrb/savon?

Related

Can not send header to vimeo using HTTParty

I want to get unauthenticated access token from vimeo api in my rails app. However the post request made using HTTParty gem returns following response from API
{"error"=>"You must provide a valid authenticated access token."}
The code to send request is
header = "basic " + Base64.encode64("****07974be" + ":" + "****ygYBI7I")
token = HTTParty.post("https://api.vimeo.com/oauth/authorize/client",
:body => {:grant_type => 'client_credentials'},
:header => {'Authorization' => header}
)
json=JSON.parse(token)
I have checked that credentials are correct and also tried replacing :header with :headers, and various combinations of using string instead of symbol in the header hash. But none of them works.
However, the call to same URL, using same credentials is successful through Postman.
Edit As mentioned in a answer, we need to use headers (plural) while making the call. However, I had already tried that but problem persists. Using basic_auth, instead of sending headers do seems to work, however I can not figure out why sending headers through HTTParty is not working but similar call is working through Postman.
The :headers option is definitely plural, but since you are using basic auth, you can also use HTTParty's basic auth option. So your request would become:
username = "YOUR-USER-HERE"
password = "YOUR-PASSWORD-HERE"
token = HTTParty.post("https://api.vimeo.com/oauth/authorize/client",
body: {:grant_type => 'client_credentials'},
basic_auth: { username: username, password: password }
)
Using your creds (did you mean to post real creds?) I got
{"access_token"=>"REDACTED", "token_type"=>"bearer", "scope"=>"public", "app"=>{"name"=>"Fable", "uri"=>"/apps/REDACTED"}}

How to make a pre-emptive basic authentication call using savon client in ruby?

I am doing the following code in savon but unable to do as it requires pre-emptive authorization. I have verified in soapUI but unable to run in savon.
Could somebody help?
client = Savon.client(ssl_verify_mode: :none) do
wsdl '/Users/sp/jda_notifications/TransportationManagerService.wsdl'
endpoint 'http://localhost:8088/webservices/services/TransportationManager'
basic_auth('VENTURE', 'VENTURE')
end
I got the exact same problem
here the solution :
realm = Base64.strict_encode64("VENTURE:VENTURE")
client = Savon.client(
wsdl:'/Users/sp/jda_notifications/TransportationManagerService.wsdl',
headers: { 'Authorization' => "Basic #{realm}"}
)
We have to use headers which edit http headers and not soap_header.

Query server with PUT method

I will replace my command line
`curl -XPUT 'host:port/url' -d '{"val": "some_json"}'̀
by a Rails command, and get the result...
Somewhere like this :
response = call('put', 'host:port/url', '{"val" : "some_json"}')
Is there any predefined method to do this in Rails, or some gem ?
I know the command get of HTTP, but I will do a 'PUT' method.
Net::HTTP.get(URI.parse('host:port/url'))
Thanks for your replies
You can use Net::HTTP to send any standard http requests.
Here is a way, you can connect to any url ( http / https ), with any valid http methods with or without parameters.
def universal_connector(api_url, api_parameters={}, method="Get")
# Do raise Error, if url is invalid and Method is invalid
uri = URI(api_url)
req = eval("Net::HTTP::#{method.capitalize}.new('#{uri}')")
req.set_form_data(api_parameters)
Net::HTTP.start(uri.host, uri.port,:use_ssl => uri.scheme == 'https') do |http|
response = http.request(req)
return response.body
end
end
There are many alternatives available as well. Specifically, Faraday. Also, read this before making a choice.
#get is just a simple shortcut for the whole code (Net::HTTP Ruby library tends to be very verbose). However, Net::HTTP perfectly supports PUT requests.
Another alternative is to use an HTTP client as a wrapper. The most common alternatives are HTTParty and Faraday.
HTTParty.put('host:port/url', { body: {"val" : "some_json"} })
As a side note, please keep in mind that Rails is a framework, not a programming language. Your question is about how to perform an HTTP PUT request in Ruby, not Rails. It's important to understand the difference.

Ruby Proxy Authentication GET/POST with OpenURI or net/http

I'm using ruby 1.9.3 and trying to use open-uri to get a url and try posting using Net:HTTP
Im trying to use proxy authentication for both:
Trying to do a POST request with net/http:
require 'net/http'
require 'open-uri'
http = Net::HTTP.new("google.com", 80)
headers = { 'User-Agent' => 'Ruby 193'}
resp, data = http.post("/", "name1=value1&name2=value2", headers)
puts data
And for open-uri which I can't get to do POST I use:
data = open("http://google.com/","User-Agent"=> "Ruby 193").read
How would I modify these to use a proxy with HTTP Authentication
I've tried (for open-uri)
data = open("http://google.com/","User-Agent"=> "Ruby 193", :proxy_http_basic_authentication => ["http://proxy.com:8000/", "proxy-user", "proxy-password"]).read
However all I will get is a OpenURI::HTTPError: 407 Proxy Authentication Required. I've verified all and it works in the browser with the same authentication and proxy details but I can't get ruby to do it.
How would I modify the code above to add http authentication properly? Has anyone gone through this atrocity?
Try:
require "open-uri"
proxy_uri = URI.parse("http://proxy.com:8000")
data = open("http://www.whatismyipaddress.com/", :proxy_http_basic_authentication => [proxy_uri, "username", "password"]).read
puts data
As for Net::HTTP, I recently implemented support for proxies with http authentication into a Net::HTTP wrapper library called http. If you look at my last pull-request, you'll see the basic implementation.
EDIT: Hopefully this will get you moving in the right direction.
Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port,"username","password").start('whatismyipaddress.com') do |http|
puts http.get('/').body
end
EDIT 11/24/2020: Net::HTTP::Proxy is now considered obsolete. You can now configure proxies when creating a new instance of Net::HTTP. See the documentation for Net::HTTP.new for more details.

Using Ruby on Rails to POST JSON/XML data to a web service

I built a web service in using Spring framework in Java and have it run on a tc server on localhost. I tested the web service using curl and it works. In other words, this curl command will post a new transaction to the web service.
curl -X POST -H 'Accept:application/json' -H 'Content-Type: application/json' http://localhost:8080/BarcodePayment/transactions/ --data '{"id":5,"amount":5.0,"paid":true}'
Now, I am building a web app using RoR and would like to do something similar. How can I build that? Basically, the RoR web app will be a client that posts to the web service.
Searching SO and the web, I found some helpful links but I cannot get it to work. For example, from this post, he/she uses net/http.
I tried but it doesn't work. In my controller, I have
require 'net/http'
require "uri"
def post_webservice
#transaction = Transaction.find(params[:id])
#transaction.update_attribute(:checkout_started, true);
# do a post service to localhost:8080/BarcodePayment/transactions
# use net/http
url = URI.parse('http://localhost:8080/BarcodePayment/transactions/')
response = Net::HTTP::Post.new(url_path)
request.content_type = 'application/json'
request.body = '{"id":5,"amount":5.0,"paid":true}'
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request) }
assert_equal '201 Created', response.get_fields('Status')[0]
end
It returns with error:
undefined local variable or method `url_path' for #<TransactionsController:0x0000010287ed28>
The sample code I am using is from here
I am not attached to net/http and I don't mind using other tools as long as I can accomplish the same task easily.
Thanks much!
url = URI.parse('http://localhost:8080/BarcodePayment/transactions/')
response = Net::HTTP::Post.new(url_path)
Your problem is exactly what the interpreter told you it is: url_path is undeclared. what you want is to call the #path method on the url variable you declared in the previous line.
url = URI.parse('http://localhost:8080/BarcodePayment/transactions/')
response = Net::HTTP::Post.new(url.path)
should work.

Resources