?
Solved

Programmatically Login

Posted on 2009-02-23
17
Medium Priority
?
805 Views
Last Modified: 2013-11-19
I would like to know how to post form data programmatically. The idea is
to get the intranet web page, programmatically enter the username and
password in a login form, post it and be redirected to the logged in
page.
0
Comment
Question by:shanemay
  • 9
  • 8
17 Comments
 
LVL 18

Accepted Solution

by:
David Robitaille earned 1500 total points
ID: 23715678
you need to check the login page to find all fields you need to post.  you need to check the url where the login button is posting.

this information is in the source of the login page.
here someting i wrote to fill a login page and press the login button for a lotus note web service.
Your problem will be to "forward" the cookie. since i keepe the cookie on the server side, it was not a problem, but i dont know how you could handle this with a response.refirect. maybe ther is a way to link those 2...

Dim webRequest As Net.HttpWebRequest
        Try
            'check if the shared SWEB Service exist, create object if not
            If _QSWEBService Is Nothing Then
                _QSWEBService = New WebService.Service()
 
                _QSWEBService.CookieContainer = New System.Net.CookieContainer()
                _QSWEBService.PreAuthenticate = True
            End If
 
 
            'first we need to test if the webservice need username and password
 
            'init the webRequest and link the WEBService cookie to the webRequest
            webRequest = Net.HttpWebRequest.Create(_QSWEBService.Url)
            webRequest.CookieContainer = _QSWEBService.CookieContainer
 
            'connect to the service 
            Dim responseReader As System.IO.StreamReader = New System.IO.StreamReader(webRequest.GetResponse().GetResponseStream())
            Dim responseData As String = responseReader.ReadToEnd()
            responseReader.Close()
 
            'check if it's the web login form
            If responseData.StartsWith("<!DOCTYPE HTML") Then
                'it's the web login form, we have to send username and password
 
                'construct the data to post
                Dim postDataByte As Byte()
                Dim userName As String = "userName"
                Dim password As String = "password"
                
                'enncode the form data string into a byte array 
                postDataByte = System.Text.Encoding.ASCII.GetBytes("username=" & userName & "&password=" & password)
 
                'create the request to the login form
                Dim LOGIN_URL As String = "http://myurl/names.nsf?Login&&RedirectTo=" & _QSWEBService.Url
                webRequest = Net.HttpWebRequest.Create(LOGIN_URL)
 
                'indicate that you will be posting the data
                webRequest.Method = "POST"
                webRequest.ContentType = "application/x-www-form-urlencoded"
                webRequest.AllowAutoRedirect = False
 
                'relink the CookieContainer to the WEBServicefor the new request
                webRequest.CookieContainer = _QSWEBService.CookieContainer
 
                'connect to the login form
                Dim postStream As System.IO.Stream = webRequest.GetRequestStream()
                'write the form values into the request message
                postStream.Write(postDataByte, 0, postDataByte.Length)
                ' Close the post
                postStream.Close()
 
                'we don't need the contents of the response, just the cookie it issues
 
                'This code is in case we want to get it (debugging) 
                'responseReader = New System.IO.StreamReader(webRequest.GetResponse().GetResponseStream())
                'responseData = responseReader.ReadToEnd()
                'responseReader.Close()
 
                webRequest.GetResponse().Close()
 
                'now we can send out cookie to the protected WEBService
                '_QSWEBService.CookieContainer = cookies
                'Don't need this line anymore, the object are directly are linked
            End If
 
            Return _QSWEBService
        Catch e As Exception
            Throw New ApplicationException("Error connecting to WEBService", e)
 
        End Try

Open in new window

0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23715697
sorry, i just noticed you are the same user one that i previously answered.
So i guess you dident find a way of doing this. where are you blocking?
 
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23715716
look at that question , i got a B on that one, but i think it should help.
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_24127907.html
 
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:shanemay
ID: 23715725
Thank you for the response. I have not found away to successfully do what I want "securely".  I have been able to duplicate this using javascript, however, it is insecure because the username and password must be placed in the html.  I know there is away to make this happen, just not sure how.
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23715794
I just got an idea, maybe you could wirte something that will play has the men in the middle by just forwarding all request to the intranet server and forward back the response using response.write
http://wiki.asp.net/page.aspx/285/httpwebrequest/
http://www.worldofasp.net/tut/WebRequest/Working_with_HttpWebRequest_and_HttpWebResponse_in_ASPNET_114.aspx
What do you think about this?
0
 

Author Comment

by:shanemay
ID: 23715858
Thank you for the reply, the sites you have given me might work.  Below is the code that I am using.  I think I will try something different tonight based on the sites you have provided.  

Uri serverUri = new Uri(string.Format(AuthenticationUrl, scheme, host));
        
        HttpWebRequest webRequest = WebRequest.Create(serverUri) as HttpWebRequest;
 
        CookieContainer owaCookies = new CookieContainer();
 
        webRequest.CookieContainer = new CookieContainer();
        webRequest.ContentType = RequestContentType;
        webRequest.Method = RequestMethod;
        webRequest.KeepAlive = true;
        webRequest.AllowAutoRedirect = false;
 
        byte[] body = Encoding.UTF8.GetBytes(string.Format(PostData, destination, domain, userName, password));
 
        webRequest.ContentLength = body.Length;
 
        using (Stream stream = webRequest.GetRequestStream())
        {
            stream.Write(body, 0, body.Length);
        }
 
        using (HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse)
        {
            foreach (Cookie aCookie in webResponse.Cookies)
            {
                owaCookies.Add(new Cookie(aCookie.Name, aCookie.Value, aCookie.Path, aCookie.Domain));
                
                HttpCookie cookie = new HttpCookie(aCookie.Name);
 
                cookie.Value = aCookie.Value;
                cookie.Path = aCookie.Path;
                cookie.Domain = aCookie.Domain;
 
                Response.Cookies.Add(cookie);
            }
        }
 
        webRequest = WebRequest.Create(destination) as HttpWebRequest;
        webRequest.CookieContainer = owaCookies;
        webRequest.ContentType = RequestContentType;
        webRequest.Method = "GET";
        webRequest.KeepAlive = true;
        webRequest.AllowAutoRedirect = true;
 
        StreamReader responseStream = new StreamReader(webRequest.GetResponse().GetResponseStream());
 
        string responseData = responseStream.ReadToEnd();
        Response.Write(responseData);

Open in new window

0
 

Author Comment

by:shanemay
ID: 23725439
I am almost there, I am getting the cookies back like I want, and I am getting into the correct mail box on exchange, however, each fame of the mail box shows the login form.  However, the url is pointing to the correct mailbox.  I know there is a way to make this work.  Any help would be appreciated.  

Thank you.
0
 

Author Comment

by:shanemay
ID: 23725546
I think the problem is that when I change the domain of the cookie, it seems to either delete the cookie, or the browser ignores it.  
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23725602

I don`t really know. I don`t know exactly what you are doing, but my intuition is that your problem is passing the cookie to the client.
My idea was not to forward the URL (and the cookie) to the client, i dont` even know if it is possible, but to forward and retrieve the request/responses to/from the intranet server. that way the client see the server though the app, like on a terminal.
 it`s also possible that approach does not even work.
I jsut read the last message and, yes i think it does not like it. I know there is a setting in IE7 to ignore 3th party cookie (under security). you should look onder page/webpage privacy policy to check if the cookie is "blocked".
I hope that will help
0
 

Author Comment

by:shanemay
ID: 23725667
Thank you for the response, I am trying to emulate a single sign on function.  I cannot imagine that I am the first person that has attempted this, however, i have not seen any code samples of this being done in the past.  Basically, I have a sql server with usernames and passwords and when the user clicks, say email, I will authenticate them to the email server, and log them in.  That is the ultimate goal, however, I am not sure that it can be done now.  Again, thank you for your help.
 
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23725773
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23736417
I was wondering how you are doing on the one and i noticed you opened a new question on that specific cookie problem.
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_24173435.html
Well, i`t a good idea since i think i gave you all I have. But i added the link for anyone who will read that question later.
Good luck
0
 

Author Comment

by:shanemay
ID: 23736602
I really appreciate your help on this issue, I have come to realize that what I want todo may not be possible. I need to find an alternative.  

Thank you for your advice and help.  
0
 

Author Closing Comment

by:shanemay
ID: 31550278
Thank you for your help.
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23837038
Simple curiosity, and for the benefit of any further reader, how do you ended on that one?
0
 

Author Comment

by:shanemay
ID: 23837063
I was not ever able to get it to work, I had to go back and have the third party services assist, they offered API's that I used.  I was never able to get it to completely work just from my end alone.  
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 23837126
Ok, I will keep that in mind. Thanks for sharing that,
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Dramatic changes are revolutionizing how we build and use technology. Every company is automating, digitizing, and modernizing operations. We need a better, more connected way to work together as teams so we can harness the insights from our system…
Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month14 days, 23 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question