Newbie Forms Question

Posted on 2005-05-16
Last Modified: 2010-04-07
I have a login page that I would like to send people to if they are not authenticated and trying to access a secure page.  I have the initial redirection to the login page working, but when I enter username and password, it doesn't go back to the page I originally requested.

The problem, as I see it, is that my sql statement isn't right.  When running profiler, this is what I see:

exec sp_executesql N'Select * from myusers where userid=@username', N'@username nvarchar(64),@password nvarchar(128)', @username = N'myname', @password = N'mypassword'

I realize I am only searching for valid usernames right now.  I am just trying to minimize the things that could be causing the issue.  Here's the code that generates the query:

        Dim Conn As SqlConnection
        Dim Cmd As SqlCommand
        Dim Reader As SqlDataReader

        Conn = New SqlConnection("workstation id=MYSERVER;packet size=4096;user id=root_user;data source=MYSERVER;persist security info=True;initial catalog=Security;password=root_pw")

        Cmd = New SqlCommand("Select * from myusers where userid=@username", Conn)

        Cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64)
        Cmd.Parameters.Add("@password", SqlDbType.NVarChar, 128)

        Cmd.Parameters("@userName").Value = username.Text
        Cmd.Parameters("@password").Value = password.Text
        Reader = Cmd.ExecuteReader()
        If (Reader.Read()) Then
            errorlabel.Text = "Connection Open."
            errorlabel.Visible = True

            Dim returnUrl As String
            returnUrl = Request.QueryString("ReturnUrl")
            errorlabel.Text = "Username / password incorrect. Please try again."
            errorlabel.Visible = True
        End If


Currently, the page shows "Connection Open" in errorlabel.Text, but the error I get in IE is:

Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: url

even though my original requesting url looks like this: http://localhost/Login/login.aspx?ReturnUrl=%2fLogin%2findex.aspx

I would like to know:

1.  What is wrong in the sql syntax that doesn't allow the where clause to be formatted and run properly?
2.  Why doesn't this code redirect and send the user to the original page they tried to login to?

If there are any better methods to do this, I am all ears.

Thanks in advance,
Question by:prairieits
    LVL 13

    Accepted Solution

            Cmd = New SqlCommand("Select * from myusers where userid=@username", Conn)
    --> you're only defining the parameter @username, but also filling  the field password. This would work better (assuming your field is called "passw"):
            Cmd = New SqlCommand("Select * from myusers where userid=@username and passw=@password", Conn)

    also, you could make it easier:
            Cmd = New SqlCommand("Select * from myusers where userid=? and passw=?", Conn)
            Cmd.Parameters.Add("userid", username.text)
            Cmd.Parameters.Add("passw", password.text)
            Reader = ...

    + another tip: you shouldn't save cleartext passwords in your database, rather just save the hashes (but this might be a big enough area for a new question ;))

    2) as soon as you've sent output to the user, you can't redirct any more. You've got the error messages (at the moment), i.e. it can't redirect.

    Hope that helped :)
    LVL 4

    Author Comment

    I can now get the label to say "Connection Open", but now how would you suggest I do the redirect?  I have my web.config setup so that if the user isn't authenticated, they are sent to the login page which I want them to be authenticated by and then sent back to the original page.

    LVL 13

    Assisted Solution

    Ah, ok, which auth-mode are you using?

    here's an example using forms authentication, this is called right after the check for user/password comes out ok:

        Function RedirectFromLoginPageEx(ByVal username As String, ByVal persistentCookie As Boolean, _
                Optional ByVal ExpirationDays As Integer = -1) As Boolean
            ' get url of resource
            Dim url As String =  FormsAuthentication.GetRedirectUrl(username, persistentCookie)
            ' create cookie
            FormsAuthentication.SetAuthCookie(username, persistentCookie)
            ' set
            If persistentCookie And ExpirationDays > 0 Then
                ' get ref to cookie, edit
                Dim cookie As HttpCookie = Response.Cookies(FormsAuthentication.FormsCookieName)
                ' set expiration
                cookie.Expires = Now.AddDays(ExpirationDays)
            End If
            ' redirect ...
        End Function

    You need to tell ASP.NET that the user is authenticated; I used SetAuthCookie. After that the user is free to roam the site (or whatever you designated).
    LVL 4

    Author Comment

    Wow Softplus!  You da man (or woman)! :)

    Thanks a ton for your help.  Does the cookie have to be persistant?  I could just say false when I call the function, right?

    Thanks again, I really appreciate it!

    LVL 13

    Expert Comment

    "da man"  :)
    I usually add a checkbox to the login form to allow the user to choose between persistant or not ("remember my login for 30 days").
    Good to see it work :)
    LVL 4

    Author Comment

    That awesome.

    Thanks again John.


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Training Course: Java/J2EE and SOA

    This course will cover both core and advanced Java concepts like Database connectivity, Threads, Exception Handling, Collections, JSP, Servlets, XMLHandling, and more. You'll also learn various Java frameworks like Hibernate and Spring.

    In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    737 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

    20 Experts available now in Live!

    Get 1:1 Help Now