# VBForums CodeBank > CodeBank - ASP / ASP.NET / MVC / Web API >  Custom Login Authentication

## Wokawidget

Unzip the code from the zip file, and create a VD in IIS called CustomAuthenticationDemo2003, which points at the dir you just unzipped.

This example uses cookies again, but this time we manually set them up. This gives you a little more contol as you can add time out limits. 

All pages inherit my base page, which is:

VB Code:
Public Class MyBasePage
    Inherits System.Web.UI.Page
     Public Sub ValidateLogin()
        Dim Cookie As HttpCookie = Request.Cookies.Item("SECURITY")
        If Cookie Is Nothing Then
            Dim RedirectPage As String = Page.ToString.Substring(4).Replace("_", ".")
            Response.Redirect("Login.aspx?Redirect=" & RedirectPage)
        End If
    End Sub
     Public ReadOnly Property Username() As String
        Get
            Dim Cookie As HttpCookie = Request.Cookies.Item("SECURITY")
            If Not (Cookie Is Nothing) Then
                Return Cookie.Values.Item("USERNAME")
            End If
        End Get
    End Property
So in your web site your pages inherit MyBaseClass.
If in the Page Load event of a form if you want to secure it from unauthorised users just add:

VB Code:
MyBase.ValidateLogin()
As you can see from the above base page code that if the cookie doesn't exist then you get redirected to the login page. I have added a little bit of code in there for a redirect once you have logged in. This is very rough code and has some problems, ie it doesn't cater for querystrings, but it's only for an example anyways.

In the login.aspx page we have the login code:

VB Code:
Private Sub Login(ByVal Username As String, ByVal Password As String)
        If ValidateLogin(Username, Password) Then
            Dim Cookie As New HttpCookie("SECURITY")
            Cookie.Values.Add("USERNAME", Username)
            Response.Cookies.Add(Cookie)
            Dim RedirectPage As String = Request.QueryString.Item("Redirect")
            If RedirectPage = String.Empty Then
                RedirectPage = "Main.aspx"
            End If
            Response.Redirect(RedirectPage)
        End If
    End Sub
As you can see if the login is validated then a new cookie is created that stores the username. This is a session based cookie.

This where it's slightly better at Forms Auth as we can now add a timeout period onto the site.
So say if our user didn't access the site for say 20 minutes, we would want their session to timeout. This can be done by adding:

VB Code:
Cookie.Expires = Date.Now.AddMinutes(20)
just after you've decalred it.

One good thing about this method is that it can be easily changed. Maybe u don't want to use cookies. Maybe you want to use SQL server and store session GUIDs, which is what we do at work. Personally I prefer the cookie method. Bu the SQL sevrer way does have it's advantages.

Woka

----------


## Wokawidget

Just to add a little extra bit of code I decided to change the validate login function in both examples to show you how to connect and validate from an SQL db.
Just replace the function with:

VB Code:
Private Function ValidateLogin(ByVal Username As String, ByVal Password As String) As Boolean
        Dim Conn As New SqlClient.SqlConnection("Your connection string here")
        Dim SQL As String
         SQL = "SELECT Password "
        SQL &= "FROM Users "
        SQL &= "WHERE Username = @Username "
         Dim Comm As New SqlClient.SqlCommand(SQL, Conn)
        Dim Param As New SqlClient.SqlParameter("@Username", SqlDbType.VarChar)
        Param.Direction = ParameterDirection.Input
        Param.Value = Username
         Comm.Parameters.Add(Param)
         Dim da As New SqlClient.SqlDataAdapter(Comm)
        Dim dt As New DataTable
         da.Fill(dt)
         Conn.Close()
        Conn.Dispose()
         Dim Validated As Boolean
         If dt.Rows.Count > 0 Then
            Validated = (dt.Rows.Item(0).Item("Password").ToString = Password)
        End If
         Return Validated
    End Function
Added password encryption may be a good idea, but I left this out to keep the example basic.

Woof

----------


## Wokawidget

One of the small problems with the latter example is that the cookie lasts 20 minutes. OK, yea this good, it's what we want. But what we don't want is for them to close IE down walk away from their computer and then someone else browsing to the site, and oh great, the cookie still lets them in. Doh!

This can be achieved by added a value to the session state.
In the Global.asax file I have:

VB Code:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        Session.Item("VALIDATED") = False
    End Sub
So, when someone opens a new session, and browses to the site, the session varible "VALIDATED" gets set to False.

So when someone logs in I want to set this to True.
I do this by doing the following in the login function in Login.aspx:

VB Code:
'rest of code
End If
 Session.Item("VALIDATED") = True 'I added this line
 Response.Redirect(RedirectPage)
'rest of code
Now in our base class we need to check for this. So I changed the ValidateLogin function to:

VB Code:
Public Sub ValidateLogin()
        Dim Cookie As HttpCookie = Request.Cookies.Item("SECURITY")
        Dim Validated As Boolean
        If Not (Cookie Is Nothing) Then
            Validated = CType(Session.Item("VALIDATED"), Boolean)
        End If
        If Not Validated Then
            Dim RedirectPage As String = Page.ToString.Substring(4).Replace("_", ".")
            Response.Redirect("Login.aspx?Redirect=" & RedirectPage)
        End If
    End Sub
This now checks for the session varible.

I have no idea if this is the correct way to go about this or not, but it works, so I am happy for now.

Please find the project attached.

WOka

----------


## Wokawidget

Here's the next installment  :Smilie: 

I have changed the Validate login function in the MyBaseClass class. 
This change now handles redirects with query strings.
The code is:

VB Code:
If Not Validated Then
            Dim Query As String = String.Empty
            For Index As Integer = 0 To Request.QueryString.Count - 1
                If Query.Length > 0 Then
                    Query &= "&"
                End If
                Query &= Request.QueryString.Keys.Item(Index)
                Query &= "="
                Query &= Request.QueryString.Item(Index)
            Next Index
             Dim RedirectPage As String = Page.ToString.Substring(4).Replace("_", ".")
             If Query.Length > 0 Then
                RedirectPage &= "?" & Query
            End If
            RedirectPage = Server.UrlEncode(RedirectPage)
            Response.Redirect("Login.aspx?Redirect=" & RedirectPage)
        End If
I also added Server.Decode in the Login page to decode the "redirect" query string. I had to encode it because you cannot have a query string in a query string as it would look like:


```
?Redirect=Users.aspx?ID=5&Task=Delete
```

ASP.NET would read this as 3 different query strings, the 1st being "Users.aspx?". For this reason we have to URL encode it.

Again, I am not sure if this is the correct way to get the query string, but I don't know of any simpler way to get it  :Frown: 

Attached is the new updated project.

Wooof

----------


## Wokawidget

OK...I've changed it again.
It now, instead of forcing you to the login page, gives you the option to force to a login page.
The base class has changed to:

VB Code:
Public Function ValidateLogin(ByVal ForceLogin As Boolean) As Boolean
        Dim Cookie As HttpCookie = Request.Cookies.Item("SECURITY")
        Dim Validated As Boolean
        If Not (Cookie Is Nothing) Then
            Validated = CType(Session.Item("VALIDATED"), Boolean)
        End If
        If Not Validated And ForceLogin Then
            Login()
        Else
            Return Validated
        End If
    End Function
     Public Sub Login()
        Response.Redirect("Login.aspx?Redirect=" & Server.UrlEncode(CurrentURL))
    End Sub
     Public ReadOnly Property CurrentURL() As String
        Get
            Return Request.Url.PathAndQuery
        End Get
    End Property
This means I can do the following in my main pages:

VB Code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If MyBase.ValidateLogin(False) Then
            btnLogin.Visible = False
            Response.Write("Hello " & MyBase.Username & ", your task today is " & MyBase.GetQueryString("Task", "***Unknown***"))
        Else
            btnLogin.Visible = True
        End If
    End Sub
     Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        MyBase.Login()
    End Sub
The above code is only an example. Maybe you want someone to view pages regardless of if they are logged in or not, but if they arn't you want to disable functionality, or show them a different control.
You can still force a login by doing:

VB Code:
MyBase.ValidateLogin(True)
I have also added some querystring functions to the base class to help my pages retieve the correct querystring in the correct format.

The code attached contains the new changes.

Woof

----------


## Wokawidget

OK. here's the next version.
I have it validating a domian user's password.
This code does not impersonate a windows user, I removed that code to make it a little more simple. 
All it does is validates the domain users password...I believe. I am still trying to look up more info on the API function:

VB Code:
Private Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer

I have moved all the user validation code to a class called Authorisation, just to keep the code neat and in one place. I have also added an enum:

VB Code:
Public Enum LoginMode
        Database = 0
        HardCoded = 1
        Windows = 2
    End Enum
Which is used when calling the ValidateUser method in the Authentication class, the ValidateUser function is:

VB Code:
Public Function ValidateLogin(ByVal Username As String, ByVal Password As String, ByVal AuthenticationMethod As LoginMode) As Boolean
        Select Case AuthenticationMethod
            Case LoginMode.Database
                Return ValidateDBLogin(Username, Password)
            Case LoginMode.HardCoded
                Return ValidateHardCodedLogin(Username, Password)
            Case LoginMode.Windows
                If Username.IndexOf("\") > 0 Then
                    Dim LoginDetails() As String = Username.Split("\"c)
                    Return ValidateWindowsLogin(LoginDetails(0), LoginDetails(1), Password)
                End If
        End Select
    End Function
I have prely done this enum for this demo. In the real world you would just pick one of those methods and ignore the rest.

When logging into a domain your username must be in the format *DOMAIN\Username*.
This then gets split up into it's individual bits when sent to the ValidateWindowsLogin function.

RobDog, I know you wanted this as a way to login, but do you want to impersonate a user, so that you can get access to resources on say the network etc...? I personally can't see the need for this and would find it pointless for what I want to do with my intranet...not sure about you.

To change the method of authentication go into the Login.aspx page and change the Login function to pass a different enum to the authentication class.

Woka

----------


## Wokawidget

Thanks to Alex_Read and Matt3011 for there help with this.
For authenticating a login against an active directory you can use:

VB Code:
Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
         Dim Success As Boolean = False
         Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
        Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
        Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
        Try
            Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
            Success = Not (Results Is Nothing)
        Catch
            Success = False
        End Try
         Return Success
     End Function
You have to reference the System.DirectorySevices in your application.
OK...I have now removed the old code that authenticated a windows account and replaced it with the above code.

I have attached the full updated project to this post.

Woof

----------


## Wokawidget

I have added some security to the cookie.
The data in the cookie is now encrypted.

WOka

----------

