jump to navigation

Creating a Login in ASP.NET using a MySQL table July 3, 2008

Posted by tuse in : ASP.NET, Databases , 2 comments

Today we will see how to create a simple login page for your ASP.NET website. Add a new WebForm to your Website. For readabilty, name this as login.aspx

Drag a Login control from the toolbox (Yes, ASP.NET comes with a built-in Login control)

This Login control is really smart and is able to do the validations itself (i.e. checking if username and password are not entered etc..)

What needs to be configured for this control is the manner in which the user authentication will occur.

We will authenticate a user using the data stored in a MySQL database in the ‘login’ table which holds the username and password (We created this table and so should you before trying this out).

Write the following code for the ‘Login1_Authenticate’ method. Double click on the Login control to goto the code window.

 

' Import the ODBC namespace for MySQL Connection
Imports System.Data.Odbc
Partial Class login
    Inherits System.Web.UI.Page

    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
        Dim cn As New OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=mydb; User=root;Password=;")
        cn.Open()
        Dim cmd As New OdbcCommand("Select * from login where username=? and password=?", cn)

        'Add parameters to get the username and password

        cmd.Parameters.Add("@username", OdbcType.VarChar)
        cmd.Parameters("@username").Value = Me.Login1.UserName

        cmd.Parameters.Add("@password", OdbcType.VarChar)
        cmd.Parameters("@password").Value = Me.Login1.Password

        Dim dr As OdbcDataReader
        ' Initialise a reader to read the rows from the login table.
        ' If row exists, the login is successful

        dr = cmd.ExecuteReader

        If dr.HasRows Then
            e.Authenticated = True
            ' Event Authenticate is true
        End If

    End Sub
End Class

Now suppose that you have other webpages in your websites and you wish to grant access to these only if a user has authenticated himself. This essentially means that the login page should appear to any anonymous users trying to access the webpage. To do this, we need to change the web.config XML file associated with the website (It is a configuration file which is added by default to all ASP.NET websites). This file can be found from the Solution Explorer (Keyboard Shortcut - Ctrl+Alt+L).

Make the following changes to the authentication tag that already exists in the file to make it look like the following-



		
        

Add a authorization tag just after the authentication to make sure anonymous users are denied access to your webpages (Anonymous users are identified by the question mark)

                                     
			             
                                     
                                     

Now when you try to request any page in your website, it shows the login.aspx to authenticate you before allowing you to view its contents.

A Login in VB.NET using Drupal Credentials June 28, 2008

Posted by tuse in : Tips and Tricks, VB.NET , add a comment

This is an interesting post in which we see the integration of the open-source technology Drupal with Microsoft .NET.

What we have already is a ‘users’ table made by Drupal. Drupal is a popular Content Management System. Whenever a user is created in a website made using Drupal, the username and password details are stored in the ‘users’ table. This password is encrypted using the MD5 algorithm and then stored in the database.

In a VB.NET application (we could as well have made a ASP.NET webpage) what we will try to do is create a login system in which the user credentials are checked against the Drupal created ‘users’ table.

In our Login form, we would need 2 Labels, 2 Textboxes, a Button and an ErrorProvider Control (We will talk about this soon). The first Tetbox is meant for the user to enter the username and the second one is meant for the password. The ErrorProvider is used to display an error message for an unsuccessful attempt at login. Once the username and password are entered, the login Button will be clicked, so we need to code the program logic in the ‘Button_Click’ event.

However, the catch here is that the password entered into the second Textbox needs to be first encrypted into its MD5 hash code before checking it against the value in the database. To accomplish this, we make use of the Function named MD5 in the code.

To check whether the value is present, we have used a DataReader object to read through the records as specified by the SQL Command Object. Note the manner in which the SQL Command is constructed. It may look to be a bit complicated at the moment, but once we tell you about connecting to databases, you will get a hold on it. The connection string that was talked about in a previous post makes an appearence here.

The code for our ‘Login’ form is as follows-

Imports System.Text
Imports System.Security.Cryptography

'This is a comment. (In case you are seeing this for the first time!)

Public Class Login

    'Function to compute MD5 for a string

    Public Function MD5(ByVal number As String) As String
        'Create an encoding object to ensure the encoding standard for the source text
        Dim ASCIIenc As New ASCIIEncoding
        Dim strReturn
        'Retrieve a byte array based on the source text
        Dim ByteSourceText() As Byte = ASCIIenc.GetBytes(number)
        'Instantiate an MD5 Provider object
        Dim Md5Hash As New MD5CryptoServiceProvider
        'Compute the hash value from the source
        Dim ByteHash() As Byte = Md5Hash.ComputeHash(ByteSourceText)
        'Cycle through the hash and convert to string
        For Each b As Byte In ByteHash
            'Convert byte(s) to string
            strReturn &= b.ToString("x2")
        Next
        'Return the result
        Return strReturn
    End Function

    Dim cn As New Odbc.OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=mydrupaldb; User=root;Password=;")

    Private Sub login_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        cn.Close()
    End Sub

    Private Sub login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        cn.Open()
        Me.Button1.Enabled = False

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Define the SQL Command to retrieve records from the database
        Dim cmd As New Odbc.OdbcCommand("select * from users where name=? and pass=?", cn)

        cmd.Parameters.Add("@name", Odbc.OdbcType.VarChar, 60)
        cmd.Parameters("@name").Value = Me.TextBox1.Text

        Dim a, b As String

        a = Me.TextBox2.Text
        b = MD5(a)

        'MD5 hash code for the password string is now held in variable b

        cmd.Parameters.Add("@pass", Odbc.OdbcType.VarChar, 32)
        cmd.Parameters("@pass").Value = b

        'We have a Data Reader to read the values returned by the SQL Command Execution
        Dim dr As Odbc.OdbcDataReader
        dr = cmd.ExecuteReader

        'Check if username and password exist. 

        If dr.HasRows = True Then
            'If exists, then we show the next form which contains the application, in my case its Form1
            Form1.Show()

        Else
            ' Incorrect Login Details Supplied
            Me.ErrorProvider1.SetError(Me.Button1, "Incorrect Login...Try again")
            Me.TextBox1.Clear()
            Me.TextBox2.Clear()
            Me.Button1.Enabled = False
        End If

    End Sub

    Private Sub TextBox2_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.LostFocus
        Me.Button1.Enabled = True
        Me.ErrorProvider1.Clear()
    End Sub


Warning: stristr() [function.stristr]: Empty delimiter in /home/tekyt17/public_html/dotnet/wp-content/plugins/wassup/wassup.php on line 2093