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.
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)
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")
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:
Code:
?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
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")
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.
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)
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.
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.