Question

i was trying to log in into a site which has the following API: POST https://www.Thesite.com/Account/LogOn post JSON data:{UserName:xxx,Pasword:xxx,SecondFactor:[optional]} save the CookieContainer & header["SecretKey"] to pass for next calls, else you will get 409 conflict I wrote the following Ruby script, but the response is : enter username and password what is wrong?

!/usr/bin/env ruby
require "rubygems"
require "httparty"

include HTTParty 

class TheSite   
  base_uri 'https://www.Thesite.com'
  def initialize(u, p)
    @data = {:UserName => u, :Pasword => p}.to_json
    response = self.class.get('/Account/LogOn')
    response = self.class.post(
      '/Account/LogOn',
       :data => @data,
       :headers=>{'SecretKey'=>response.headers['Set-Cookie']})
       @cookie = response.request.options[:headers]['cookie']
    puts response
  end
end

thesite = Thesite.new('myuser', 'mypassword')

No correct solution

OTHER TIPS

There's a fair bit incorrect here:

  • You don't need to JSONify the data, but you need to set the correct JSON headers. A lot of people do this don't worry.
  • The whole cookie thing comes after the request, not in it.
  • Some missing brackets here swell.

Here's a working example:

!/usr/bin/env ruby
require "rubygems"
require "httparty"

include HTTParty 

class TheSite   
  base_uri 'https://www.Thesite.com'
  def initialize(u, p)
    @data = {
      :UserName => u,
      :Password => p
    } 
    res = self.class.post('Account/LogOn', 
                          :body => @data, 
                          :options => {
                            :headers => { 
                              'ContentType' => 'application/json', 
                              'Accept'      => 'application/json',
                              'SecretKey'   => res.headers['Set-Cookie']                          
                            }
                          }
                         )
    if res.code == 200
      @cookie = res.request.options[:headers]['Cookie']
      # do stuff
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top