Search code examples
ruby-on-railsrubychef-infrachef-recipecookbook

How to Parse uri in ruby without Authentication


My Code,

require 'net/http'
require 'json'

url = 'http://api.spotify.com/v1/search?type=artist&q=tycho'
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
puts(response)

This works as long as it is http but the instance it is https it fails with Authentication error.

Actual Error: SSL_connect returned=1 errno=0 state=error: certificate verify failed (error number 1) (OpenSSL::SSL::SSLError)

In Curl I can use insecure mode which helps get the results as shown in the example below:

curl --insecure -X GET -H "content-type: application/json" -H "Accept: application/json" -d '{}' "http://api.spotify.com/v1/search?type=artist&q=tycho"

What would the equivalent method be for "net/http" method where i could add insecure or validation=false.

I will be using the output to append a recipe in CHEF.

NOTE: The correct URI will be different and not the one mentioned in the above link

Any leads is greatly appreciated.

Thank you Anish


Solution

  • To turn off certificate verification, try this:

    require 'net/http'
    require 'json'
    require 'openssl'
    
    url = 'https://api.spotify.com/v1/search?type=artist&q=tycho'
    uri = URI(url)
    http = Net::HTTP.new(uri.host, uri.port)
    
    http.use_ssl     = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    
    response = http.request_get(uri.path).body
    JSON.parse(response)
    puts(response)