ruby-on-railsrubycookiesfaraday

Creating a cookie to send with faraday GET request


I am trying to trigger a GET request where I need to send two cookies (I obtain these through inspecting my browser cookies once I authenticate into my website) that authorises my request. However, when I try the below ruby code using the faraday gem I receive an unauthorised access error, which isn't the case when I use postman to send the same cookie data ( https://learning.postman.com/docs/sending-requests/cookies/). Can anyone see what I am doing wrong?

url = "https://someurl.com/random_data"
  resp = Faraday.get(url) do |req|
    req.headers['cookie'] = '{"credential_1":' + @credentials["credential_1"] + ',"credential_2":' + @credentials["credential_2"]}'
  end

Solution

  • The wasn't working due to a misconstructed cookie (needed to be pieced together with a ';'). By following this answer https://stackoverflow.com/a/42911732/427499 I rewrote the assembly of the cookie to look like the below which now works.

    url = "https://someurl.com/random_data"
    resp = Faraday.get(url) do |req|
      cookie_hash = {"credential_1" => @auth_credentials["credential_1"], "credential_2" => @auth_credentials["credential_2"]}
    
      req.headers['Cookie'] = cookie_hash.map { |key, value| "#{key}=#{value}" } .join('; ')
    end