使用Faraday请求LibreNMS API返回登录重定向HTML而非JSON问题排查
Hey, let's figure out why your Faraday call is getting redirected to the login page while curl works perfectly. The key difference I spot right away is the path you're using in each request:
- Your curl command hits
https://librenms.mydomain.nl/api/v0/ports/25008 - But your Faraday code is requesting
/ports/25008.json(which becomeshttps://librenms.mydomain.nl/api/v0/ports/25008.json)
LibreNMS's API endpoints don't expect the .json suffix—you've already configured Faraday to handle JSON responses with conn.response :json, and curl works fine without it. When you add .json, LibreNMS doesn't recognize that as a valid API route, so it treats it like a regular web request that requires authentication, hence the redirect to login.
Here's how to fix it:
Remove the
.jsonfrom your request path
Update yourcallmethod to match the path you used in curl:def call() response = libre_connection.get "/ports/25008" endWith your
path_prefix = "/api/v0"already set, Faraday will build the correct URL:https://librenms.mydomain.nl/api/v0/ports/25008—exactly what worked with curl.Optional: Double-check redirect handling
If you still run into issues, you can explicitly add Faraday's redirect middleware to ensure it follows any legitimate redirects (though this shouldn't be necessary here):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" # Add redirect middleware to follow up to 3 redirects conn.use FaradayMiddleware::FollowRedirects, limit: 3 conn.adapter Faraday.default_adapter end endBut the main culprit here is definitely the extra
.jsonsuffix, so start with that change first.
After making this adjustment, your Faraday request should return the same JSON response as your curl command. LibreNMS will recognize it as a valid API request with a valid token, so no more login redirects!
内容的提问来源于stack exchange,提问作者perkoei

