locked
Log-in form - couple of questions RRS feed

  • Question

  • User-1793215261 posted

    Hello

    I have a 'register new user form' in VB.NET, Register.aspx, and have introduced the default 'Log in' form from Solution Explorer to my project.

    The Log in button now has this code:

    <div class="form-group"><div class="col-md-offset-2 col-md-10">
    <asp:Button ID=btnLogin runat="server" OnClick="LogIn" Text="Log in" CssClass="btn btn-default" /> 
    
    </div>
       </div>

    I am not sure that this looks correct: OnClick="LogIn" because once the user has logged on, shouldn't he be taken to a Web page that is otherwise concealed as in: www.myHiddenPage.html?

    In the accompanying Login.aspx.vb page, I have:

    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.EntityFramework 
    Imports Microsoft.AspNet.Identity.Owin
    Imports System.Linq
    Imports System.Web
    Imports System.Web.UI
    Imports Microsoft.Owin.Security
    
    Public Partial Class Account_Login
    
        Inherits Page     
    
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load         
    
    RegisterHyperLink.NavigateUrl = "Register"         OpenAuthLogin.ReturnUrl = Request.QueryString("ReturnUrl")         
    
    Dim returnUrl = HttpUtility.UrlEncode(Request.QueryString("ReturnUrl"))         
    
    If Not [String].IsNullOrEmpty(returnUrl) Then             
    
    RegisterHyperLink.NavigateUrl += "?ReturnUrl=" & returnUrl         
    
    End If     
    
    End Sub
    
    
    
    
    Protected Sub LogIn(sender As Object, e As EventArgs) Handles btnLogin.Click
    
    If IsValid Then             ' Validate the user password             
    
    Dim manager = New UserManager()             
    
    Dim user As ApplicationUser = manager.Find(username.Text, password.Text)            
    
    If user IsNot Nothing Then                
    
    IdentityHelper.SignIn(manager, user, RememberMe.Checked)                
    
    IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)             
    
    Else                 
    
    FailureText.Text = "Invalid username or password."                 
    
    ErrorMessage.Visible = True             
    
    End If         
    
    End If     
    
    End Sub End Class
    

    username and password are the names of my form fields and two columns in my MS Access database.

    Does this script inherit the database connection values from Register.aspx or do I have to give Login.aspx its own Web config file and use SQL SELECT etc to verify that this user does exist in the database. I can't find appropriate guidelines or examples on the WWW: those tutorials tend to use Log-in forms built from scratch.

    Thank you.

    Saturday, September 20, 2014 3:55 PM

All replies

  • User1292124637 posted

    It looks correct to me. Have you tried testing it?

    I would recommend running your app / website in VS and walking through the registration page yourself.

    After which, you can test out the login form.

    At first glance, it looks like your LogIn sub, redirects successfully logged in users to a ReturnUrl.

    Also, it looks like the Login sub is querying the standard membership database that gets created with whatever template you used. Otherwise, I think it's using UserManager() to query any available membership_type database.

    Saturday, September 20, 2014 6:23 PM
  • User-1793215261 posted

    Hello

    Thanks for your reply.

    In my Access database I have 'coffee' as a username and 'coffee1' as the password, but when I preview my log-in form through a browser (IE11) and try to log in with 'coffee' and 'coffee1', I get the following error:

    Invalid username or password.

    That means the code is not recognising the data inserted in the database, doesn't it? What may be the cause of that, please?

    Sunday, September 21, 2014 8:22 AM
  • User1292124637 posted

    Yeah it's probably failing at:

        If user IsNot Nothing Then                
    
           IdentityHelper.SignIn(manager, user, RememberMe.Checked)                
    
           IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)             
    
        Else                 
    
           FailureText.Text = "Invalid username or password."                 
    
           ErrorMessage.Visible = True             
    
        End If         

    We can try catching and displaying the actual error by encapsulating it in a try / catch statement and displaying the exception, like so:

    Protected Sub LogIn(sender As Object, e As EventArgs) Handles btnLogin.Click
    
      If IsValid Then             ' Validate the user password             
    
        Dim manager = New UserManager()             
    
        Dim user As ApplicationUser = manager.Find(username.Text, password.Text)
        
        try         
    
          If user IsNot Nothing Then                
    
             IdentityHelper.SignIn(manager, user, RememberMe.Checked)                
    
             IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)                        
    
          End If
        
        catch ex As Exception 
    
           FailureText.Text = ex.Message
    
           ErrorMessage.Visible = True              
    
      End If     
    
    End Sub End Class

    The ex.Message should pump out the actual failure error onto the screen. Let me know what is says.

    Sunday, September 21, 2014 2:45 PM
  • User-1793215261 posted

    I had to use the following otherwise I got blue underlined errors:

     Try
                    If user IsNot Nothing Then
                        IdentityHelper.SignIn(manager, user, RememberMe.Checked)
                        IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
                    Else
    
                    End If
    
                Catch ex As Exception
    
                End Try
    
                FailureText.Text = "Invalid username or password."
                ErrorMessage.Visible = True
            End If
    
        End Sub

    No text-box pops up and I can see the form as normal in the browser preview.

    Sunday, September 21, 2014 3:45 PM
  • User1292124637 posted

    Sorry about that, I did not close it properly. Try this:

    Protected Sub LogIn(sender As Object, e As EventArgs) Handles btnLogin.Click
    
      If IsValid Then             ' Validate the user password             
    
        Dim manager = New UserManager()             
    
        Dim user As ApplicationUser = manager.Find(username.Text, password.Text)
        
        Try         
    
          If user IsNot Nothing Then                
    
             IdentityHelper.SignIn(manager, user, RememberMe.Checked)                
    
             IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)                        
    
          End If
        
        Catch ex As Exception 
    
           FailureText.Text = ex.Message 'this should pump out the actual error line from the stack trace.
    
           ErrorMessage.Visible = True
    
        End Try              
    
      End If     
    
    End Sub

    I think the above is correct.

    You can always use something else instead of FailureText.Text = ex.Message to pump out the actual error message.

    You can just create a new string variable called message and assign ex.message to it on Catch Ex as exception.

    Or, since you're running this in VS, you can always pump it all out to console:

    Console.WriteLine("Exception: " & ex.Message)
    

    Thursday, September 25, 2014 9:18 PM
  • User-1793215261 posted

    Hello

    Thanks for all your work.

    I have copied and pasted your script and then pressed F5. Is that what you mean? This is what I can see:

    There are no text-boxes informing me of errors.

    I have previewed the file in my browser, completed the form, pressed submit, and nothing happens. I remain on that page and, again, there are no error messages.

    Thanks again.

    Friday, September 26, 2014 10:22 AM
  • User1292124637 posted

    I see. I'm gonna fire up VS and try running this myself. By the looks of it, there should be no errors and the code is proper. I'll get back to you in a bit.

    Friday, September 26, 2014 2:15 PM
  • User-1793215261 posted

    Thanks!

    Friday, September 26, 2014 2:48 PM
  • User1292124637 posted

    OK, so for your Login.aspx.vb page, this should be the code only:

    Partial Class Account_Login
        Inherits Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            RegisterHyperLink.NavigateUrl = "Register"
            OpenAuthLogin.ReturnUrl = Request.QueryString("ReturnUrl")
    
            Dim returnUrl = HttpUtility.UrlEncode(Request.QueryString("ReturnUrl"))
            If Not String.IsNullOrEmpty(returnUrl) Then
                RegisterHyperLink.NavigateUrl &= "?ReturnUrl=" & returnUrl
            End If
        End Sub
    End Class

    If you've already registered and are trying to log in, the above code will redirect you to the homepage.

    For your register.aspx.vb, this should be your code only:

    Imports Microsoft.AspNet.Membership.OpenAuth
    
    Partial Class Account_Register
        Inherits Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            RegisterUser.ContinueDestinationPageUrl = Request.QueryString("ReturnUrl")
        End Sub
    
        Protected Sub RegisterUser_CreatedUser(ByVal sender As Object, ByVal e As EventArgs) Handles RegisterUser.CreatedUser
            FormsAuthentication.SetAuthCookie(RegisterUser.UserName, createPersistentCookie:=False)
    
            Dim continueUrl As String = RegisterUser.ContinueDestinationPageUrl
            If Not OpenAuth.IsLocalUrl(continueUrl) Then
                continueUrl = "~/"
            End If
    
            Response.Redirect(continueUrl)
        End Sub
    End Class

    If you register successfully, the above code will redirect you to the homepage.

    Friday, September 26, 2014 6:03 PM
  • User-1793215261 posted

    Many thanks for that!

    I will give it a try and post.

    Much appreciated.

    Sorry for the delay in replying.

    Saturday, October 4, 2014 5:40 PM
  • User-1793215261 posted

    Hello Angel of Death

    Yes, I have exactly what you have for login.aspx.vb.

    My Register.aspx.vb is very different from what you have. It looks like this:

    Imports Microsoft.AspNet.Identity
    Imports Microsoft.AspNet.Identity.EntityFramework
    Imports Microsoft.AspNet.Identity.Owin
    Imports System
    Imports System.Linq
    Imports System.Web
    Imports System.Web.UI
    Imports System.Data.OleDb
    
    Partial Public Class Account_Register
        Inherits Page
    
        Protected Sub Page_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs)
            username.Focus()
        End Sub
    
        Protected Sub CreateUser1_Click(sender As Object, e As EventArgs)
    
    
            Using conn As OleDbConnection = New OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings("students").ConnectionString)
    
                Dim Sql As String = "INSERT INTO university (username,[password],strEmail) VALUES (@username,@password,@strEmail)"
                Dim cmd As New OleDbCommand(Sql, conn)
                conn.Open()
                cmd.Parameters.AddWithValue("@username", username.Text)
                cmd.Parameters.AddWithValue("@password", password.Text)
                cmd.Parameters.AddWithValue("@strEmail", strEmail.Text)
                cmd.ExecuteNonQuery()
                conn.Close()
    
            End Using
    
            'Response.Redirect("success.aspx", True)
            'Response.Redirect("success.aspx", True)
    
            'Response.Redirect("~/success.aspx", True)
    
            'Response.Redirect("success.aspx?Data=" & Server.UrlEncode(username.Text))
            'Response.Redirect("~/success.aspx?Data=" & Server.UrlEncode(username.Text))
    
            ' Build your target URL (appending the name of your user) '
            'Dim target = String.Format("~/Success.aspx?Name={0}", username)
    
            ' Perform your Redirect '
            'Response.Redirect(target, True)
    
            Dim target = String.Format("~/success.aspx?Name={0}", username.Text)
            ' Perform your Redirect '
            Response.Redirect(target, True)
    
    
        End Sub
    
    End Class

    When you say 'If you've already registered and are trying to log in, the above code will redirect you to the homepage', what do you mean by homepage? I ask because I have not indicated in any part of the scripts for the Register or Login.aspx files, what that homepage is. The homepage is a Classic ASP page that is hosted by an external Web site. It's already on the Internet, so after logging in the user should be redirected there.

    Also, in my Login.aspx.vb script, don't I need statements such as SELECT FROM table etc plus a reference to the database?

    Thanks again.

    Monday, October 6, 2014 1:17 PM