Programmatically Login

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
Who is Participating?
David RobitailleAnalyst ProgrammerCommented:
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
            '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()
            '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
                '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()
                '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

David RobitailleAnalyst ProgrammerCommented:
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?
David RobitailleAnalyst ProgrammerCommented:
look at that question , i got a B on that one, but i think it should help.
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

shanemayAuthor Commented:
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.
David RobitailleAnalyst ProgrammerCommented:
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
What do you think about this?
shanemayAuthor Commented:
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;
        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();

Open in new window

shanemayAuthor Commented:
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.
shanemayAuthor Commented:
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.  
David RobitailleAnalyst ProgrammerCommented:

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
shanemayAuthor Commented:
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.
David RobitailleAnalyst ProgrammerCommented:
David RobitailleAnalyst ProgrammerCommented:
I was wondering how you are doing on the one and i noticed you opened a new question on that specific cookie problem.
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
shanemayAuthor Commented:
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.  
shanemayAuthor Commented:
Thank you for your help.
David RobitailleAnalyst ProgrammerCommented:
Simple curiosity, and for the benefit of any further reader, how do you ended on that one?
shanemayAuthor Commented:
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.  
David RobitailleAnalyst ProgrammerCommented:
Ok, I will keep that in mind. Thanks for sharing that,
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.