1

I'm using the Faraday gem to request some data from the LibreNMS API. But when i display the response body I get some HTML code that looks like a redirect page to the libreNMS login.

I have the following code (BaseService class):

def libre_connection
Faraday.new(url: 'https://librenms.mydomain.nl') do |conn|
  conn.path_prefix = "/api/v0"
  conn.response :json, :content_type => /\bjson$/, :parser_options => { :symbolize_names => true }

  conn.headers['X-Auth-Token'] = Rails.application.credentials[:libre][:key]
  conn.headers["Content-Type"] = "application/json"



  conn.adapter Faraday.default_adapter

end

And then this in a class that extends BaseService

def call()
    response = libre_connection.get "/ports/25008.json"
end

For some reason this gives the following response:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="0;url=https://librenms.mydomain.nl/login" /> <title>Redirecting to https://librenms.mydomain.nl/login</title> </head> <body> Redirecting to <a href="https://librenms.mydomain.nl/login">https://librenms.mydomain.nl/login</a>. </body> </html> 

I know the token works because when I do the following curl command I get the JSON response I expect

curl -H 'X-Auth-Token: MYAPITOKEN' https://librenms.mydomain.nl/api/v0/ports/25008

Anyone have any idea what I'm doing wrong?

Acapulco
  • 3,373
  • 8
  • 38
  • 51
perkoei
  • 11
  • 1
  • What response do you get from curl with an incorrect/missing `X-Auth-Token` header? Are you sure `Rails.application.credentials[:libre][:key]` is giving you the valid token? – ramblex Nov 29 '19 at 17:07
  • You're trying to connect over `https` right? Have a look at https://github.com/lostisland/faraday/wiki/Setting-up-SSL-certificates – lacostenycoder Nov 29 '19 at 21:13

2 Answers2

0

You're trying to connect over HTTPS. For local development you can try:

def libre_connection
  Faraday.new(url: 'https://librenms.mydomain.nl') do |conn|
    conn.ssl.verify = false # DONT DO THIS IN PRODUCTION
    conn.path_prefix = "/api/v0"
    conn.response :json, :content_type => /\bjson$/, :parser_options => { :symbolize_names => true }

    conn.headers['X-Auth-Token'] = Rails.application.credentials[:libre][:key]
    conn.headers["Content-Type"] = "application/json"

    conn.adapter Faraday.default_adapter
  end
end

For production see https://github.com/lostisland/faraday/wiki/Setting-up-SSL-certificates for how to properly configure SSL.

lacostenycoder
  • 10,623
  • 4
  • 31
  • 48
0

Thanks for the reply's guys, I figured it out. The problem was in the class that extends BaseService this is what it looks like now:

class LibrenmsApi::ConnectionsService < LibrenmsApi::BaseService
def call()
    response = libre_connection.get "ports/25008"
end
end

note the "ports/25008" part. I removed the '/' at the beginning and that fixed it.

perkoei
  • 11
  • 1