Hi,
I’m trying to write a program which will try to login to my web site
by passing user & password. The site is in ASP.net for which I’m trying
to authenticate.
Somehow, I’m having problem with fetching cookies from the response &
passing it to next request.
Can you please tell me how to retrieve cookies from response in ruby?
I do not want to extract just set-cookie as I tried that & its not
working. Some how its not giving me complete cookie & hence I’m getting
back the login page itself.
Here is the code snippet
servicehost = Config::ADMIN_HOST
serviceport = Config::ADMIN_PORT
accountname = Config::ADMIN_ACCOUNT_NAME
accountpwd = Config::ADMIN_ACCOUNT_PWD
monitorid = Config::USER_AGENT
loginpage = Config::ADMIN_LOGINPAGE
http = Net::HTTP.new(servicehost, serviceport)
http.use_ssl = false
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start do |http|
request1 = Net::HTTP::Get.new(loginpage, {"User-Agent" => monitorid})
response1 = http.request(request1)
puts "1st Code = #{response1.code}"
location = response1.response['location']
puts "location=#{location}"
request1 = Net::HTTP::Get.new(location, {"User-Agent" => monitorid})
response1 = http.request(request1)
puts "2nd Code = #{response1.code}"
puts "2nd cookie= #{response1.response['set-cookie']}"
/__VIEWSTATE" value="(.*)"/.match(response1.body)
viewstate = $1
/WebForm_Do(.*)"/.match(response1.body)
eventvalidation = $1
eventvalidation = URI.escape(eventvalidation)
puts eventvalidation
req = Net::HTTP::Post.new(location, {"User-Agent" => monitorid,
'Content-Type' => 'application/x-www-form-urlencoded'})
req.set_form_data({'txtLogin_LoginPage'=>accountname,
'txtPassword_LoginPage'=>accountpwd, 'btnLogin'=>'Login',
'__EVENTTARGET'=>'', '__EVENTARGUMENT'=>'',
'__EVENTVALIDATION'=>eventvalidation, '__VIEWSTATE'=>viewstate})
response = http.request(req)
redirect = false
case response
when Net::HTTPSuccess
#puts "OK"
when Net::HTTPRedirection
redirect = true
else
inerror = true
end
puts "3rd Code = #{response.code}"
puts "Message = #{response.message}"
response.each {|key, val| printf "%s= %s\n", key, val }
resp = response.body
if redirect
request = Net::HTTP::Get.new(loginpage, {"User-Agent" =>
monitorid})
# Below line some how does not work. Can some one provide cookie
container object code?
request.add_field 'Cookie', response.response['set-cookie']
response = http.request(request)
resp = response.body
print resp
end
end