login using WebRequest

Posted on 2012-09-05
Last Modified: 2012-09-10
See below code.  I copied this snippet of code from something I googled.  I want to login to a WEB page that uses a separate logon page.  When this executes, I get a status code of 200 and a status description of "OK", so all is well.  However, it does not login.   The response data I get back is just the login page.  It does not take me to the page it should after the login.  

Can anyone help me?  Why does it not login in?   Login1$UserName and Login1$Password are the ID's of the HTML elements of the login page.

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim postDataString As String = ""
        postDataString += "Login1$UserName" & "=" & "xxxxx"
        postDataString += "&Login1$Password" & "=" & "yyyyyy"
        ' here the &username and &password
        ' tags should be the same as used in web page form which can be seen using View Source for the
        'html page

        Dim asciiEncoding As New System.Text.ASCIIEncoding()
        Dim postDataBytes As Byte() = asciiEncoding.GetBytes(postDataString)

        Dim uriLoginForm As New Uri("")

        Dim webRequest__1 As HttpWebRequest = DirectCast(WebRequest.Create(uriLoginForm), HttpWebRequest)
        webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
        ' webRequest__1.Referer = ""

        ' actual website address here
        webRequest__1.KeepAlive = True
        webRequest__1.Method = "POST"
        webRequest__1.ContentType = "application/x-www-form-urlencoded"
        webRequest__1.ContentLength = postDataBytes.Length
        webRequest__1.AllowAutoRedirect = True
        webRequest__1.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"

        Dim outStream As System.IO.Stream = webRequest__1.GetRequestStream()
        outStream.Write(postDataBytes, 0, postDataBytes.Length)

        Dim webResponse As HttpWebResponse = DirectCast(webRequest__1.GetResponse(), HttpWebResponse)
        Dim streamReader As StreamReader = New System.IO.StreamReader(webResponse.GetResponseStream())
        Dim respString As String = streamReader.ReadToEnd()

        Dim s As String = webResponse.StatusCode
        s = webResponse.StatusDescription




    End Sub
Question by:HLRosenberger
    LVL 26

    Accepted Solution

    Not really SQL syntax, but maybe this will help:
    <%@ Page Language="VB" %>
    <%@ Import Namespace="System" %>
    <%@ Import Namespace="System.IO" %>
    <%@ Import Namespace="System.Net" %>
    <%@ Import Namespace="System.Text" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    <script runat="server">
      Protected Sub Button1_Click(sender As Object, e As System.EventArgs)
        Dim UserName As String = "Alan"
        Dim Password As String = "shhh_secret"
        Dim Domain As String = "http://localhost/the-website/"
        ' The following folder and file should exist in your web
        ' The folder is protected by web.config deny unauthenticated users (<deny users="?"/>)
        Dim RequestUri As String = "http://localhost/the-website/securefolder/top-secret.aspx"
        ' Call the constructor  to create an instance of NetworkCredential with the 
        ' specified user name and password. 
        Dim myCredentials As New NetworkCredential(UserName, Password)
        ' Create a WebRequest with the specified URL.  
        Dim myWebRequest As WebRequest = WebRequest.Create(RequestUri)
        myCredentials.Domain = Domain
        myWebRequest.Credentials = myCredentials
        ' Send the request and wait for a response. 
        Dim myWebResponse As WebResponse = myWebRequest.GetResponse()
        With myWebResponse
          ' the response uri differs from the original requested uri, we are being redirected to the login page!
          If .ResponseUri <> myWebRequest.RequestUri Then
            ' try to login using the credentials we have
            If Membership.ValidateUser(UserName, Password) Then
              FormsAuthentication.RedirectFromLoginPage(UserName, True)
              ' get the web root path
              Dim strRoot As String = ""
              If Request.IsSecureConnection Then
                strRoot = String.Format("https://{0}{1}", Request.Url.Host, Page.ResolveUrl("~/"))
                strRoot = String.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl("~/"))
              End If
              ' convert the original reqested uri to a relative path and redirect.
              Response.Redirect(RequestUri.Replace(strRoot, "~/"), False)
            End If
          End If
        End With
        ' Release the resources of the response object.
      End Sub
    <html xmlns="">
    <head runat="server">
        <form id="form1" runat="server">
          <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

    Open in new window

    Alan ";0)
    LVL 1

    Author Comment


    Oh, sorry... Posted in the wrong area....
    LVL 1

    Author Comment

    I've requested that this question be deleted for the following reason:

    Posted in wrong area.
    LVL 26

    Expert Comment

    by:Alan Warren
    Maybe just move the question, rather than delete it, perhaps asp .net programming may be a more appropriate TA; invested a bit of time in this already.

    Respectfully yours,
    LVL 1

    Author Comment

    OK  Thanks. So now what do I do with this question?
    LVL 1

    Author Comment

    OK.  I choose the wrong area.  My mistake.  So, what now to do with this question?
    LVL 26

    Expert Comment

    by:Alan Warren
    The possible solution I posted most definitely logs in using a WebRequest.

    Respectfully yours,
    LVL 1

    Author Closing Comment


    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Preface In the first article: A Better Website Login System ( I introduced the EE Collaborative Login System and its intended purpose. In this article I will discuss some of the design consideratio…
    This demonstration started out as a follow up to some recently posted questions on the subject of logging in: and…
    Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
    The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

    729 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

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now