PDA

Click to See Complete Forum and Search --> : Windows Authentication


RobDog888
Jul 13th, 2005, 12:55 AM
I'm finally getting around to ASP.NET authentication for a page and its not validating for some reason. :(

Here is my code (ASP.NET 1.1).
Option Explicit On

Imports System.Security.Principal
Imports System.Runtime.InteropServices

Public Class index3

Inherits System.Web.UI.Page

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
Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, ByVal ImpersonationLevel As Integer, ByRef DuplicateTokenHandle As IntPtr) As Integer
Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long

Private LOGON32_LOGON_INTERACTIVE As Integer = 2
Private LOGON32_PROVIDER_DEFAULT As Integer = 0

Private impersonationContext As WindowsImpersonationContext

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Me.txtUsername.Text = "Domain\Username"
'Me.txtPassword.Text = String.Empty
End Sub

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
If impersonateValidUser(Me.txtUsername.Text, Me.txtPassword.Text) Then
'MessageBox.Show("User authenticated sucessfully")
'Insert your code that runs under the security context of a specific user here.
Response.Redirect("index2.aspx")
undoImpersonation()
Else
'MessageBox.Show("Invalid password or user")
'Your impersonation failed. Therefore, include a fail-safe mechanism here.
Response.Redirect("index.aspx")
End If
End Sub

Private Function impersonateValidUser(ByVal userName As String, ByVal password As String) As Boolean

Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr = IntPtr.Zero
Dim tokenDuplicate As IntPtr = IntPtr.Zero
Dim ar() As String
Dim domain As String
impersonateValidUser = False
ar = userName.Split("\")
If UBound(ar) = 0 Then
CloseHandle(token)
Exit Function
Else
domain = ar(0)
userName = ar(1)
End If
If RevertToSelf() Then
If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
impersonationContext = tempWindowsIdentity.Impersonate()
If Not impersonationContext Is Nothing Then
impersonateValidUser = True
End If
End If
End If
End If
If Not tokenDuplicate.Equals(IntPtr.Zero) Then
CloseHandle(tokenDuplicate)
End If
If Not token.Equals(IntPtr.Zero) Then
CloseHandle(token)
End If
End Function

Private Sub undoImpersonation()
impersonationContext.Undo()
End Sub

mendhak
Jul 13th, 2005, 01:25 AM
What are you trying to do?

RobDog888
Jul 13th, 2005, 10:01 AM
Authenticate users to log in to a web page using Windows auth.

Wokawidget
Jul 13th, 2005, 10:45 AM
errr...ASP.NET does this for you automatically.
No need for all that code at all :(

Have:

<authentication mode="Windows" />

In your config file.
And then...
Go into IIS, go to properties of VD, then Directory Security, and untick anonamous access, 1st tick box on form.

This is all you need.

Unless of course you want to be a little cleverer.
I am sure you don't need those API functions there, as I believe .NET can do this in System. blah blah somewhere.

Woof

mendhak
Jul 13th, 2005, 11:03 AM
Wow... I've never seen so much code for an existing feature. :sick:

You should google a few articles on "ASP.NET" Windows authentication

RobDog888
Jul 13th, 2005, 11:17 AM
But I got the code from the link Woka posted a few months ago. Here it is (http://www.vbforums.com/showthread.php?t=328975). I'm barely starting on this. :blush: I have been busy posting :lol:

mendhak
Jul 13th, 2005, 11:23 AM
But I got the code from the link Woka posted a few months ago. Here it is (http://www.vbforums.com/showthread.php?t=328975). I'm barely starting on this. :blush: I have been busy posting :lol:
That's what you get for listening to him instead of me ;)


Woka:

*SLAP*

Silly badger. :lol:

Wokawidget
Jul 13th, 2005, 11:35 AM
when did I post that code?!!! Never seen it in my life before :(
U don't need any code for windows auth!
U ONLY have to make the change in your config file, and the IIS VD properties.
That's it.
.NET handles everything else for you.

Oh I see...u want to write your own login screen. Ahhhhh.

What benefits are you gonna get from using windows auth? and not forms auth?

Woka

RobDog888
Jul 13th, 2005, 11:41 AM
Still n00b here for ASP.NET even though the thread was 4 months old. :D

I want to create a page with a left "sidebar" or menu that will have two small textboxes for employee login to a different section
of the site. They dont like the windows popup login.

Wokawidget
Jul 13th, 2005, 11:46 AM
OK. no probs, I would want to do exactly the same and write my own login page. Does it have to be windows auth?
Can you not create your own SQL Server DB with a users tabale?

Or even more basic...add their names and passwords to the config file. I personally don't like this method.

I much prefer the SQL method.

Woka

RobDog888
Jul 13th, 2005, 11:51 AM
I thought about the SQL method too but I dont like exposing SQL to the internet and having to manage the usernames and passwords.
The code doesnt error or anything, just doesnt seems to get past the line with "LogonUserA" :(

Wokawidget
Jul 13th, 2005, 12:01 PM
Have a read of this on the MS web site.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecurityprincipalwindowsimpersonationcontextclasstopic.asp

That is what you want isn't it?

I find Forms Auth much more customisable...Yea you have to add users and stuff, but as for future development and deployment, I think it's the way forward.

WOka

RobDog888
Jul 13th, 2005, 12:17 PM
Can you tell me more on this "Forms Auth" subject? :D

Wokawidget
Jul 13th, 2005, 03:23 PM
OK. I am writing you 2 demo projects. One uses Forms authentication, and one is a good custom method, which does the same as forms authentication, but it's all done manually.

Give me about 20mins or so, and I'll post the project.

WOof

Wokawidget
Jul 13th, 2005, 03:56 PM
Ok here's a quick demo of basic forms authentication.
The only real code I have coded is in the login page, and the config file.
In the web.config file I have:

<authentication mode="Forms">
<forms name=".DEMOAPP" loginUrl="Login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>

This means that if the cookie DEMOAPP doesn't exist, or is invalid, then everyone gets redirected to the login.aspx page.

Maybe you want certain pages that anonamous users, not logging in, can view.
To do this I have added some extra lines to my config file:

'other config stuff
</system.web>

'I have added this
<location path="Main.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>

</configuration>

This basically tells .net that anyone can view Main.aspx, logged in or not.

I have used the username Woof and password Growl in my exmaples to validate my login.

My login code looks like:

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Login(txtUsername.Text, txtPassword.Text)
End Sub

Private Sub Login(ByVal Username As String, ByVal Password As String)
If ValidateLogin(Username, Password) Then
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(Username, False)
End If
End Sub

Private Function ValidateLogin(ByVal Username As String, ByVal Password As String) As Boolean
'here you would query your SQL DB as you would with a nomral app
'but in this case I have hard coded a username and password in.

Return (Username = "Woof") And (Password = "Growl")
End Function

The following line is the one that saves the security cookie to the clients PC:

System.Web.Security.FormsAuthentication.RedirectFromLoginPage(Username, False)

The username can be got at any time using:

Response.Write(User.Identity.Name)

As I have done in my users.aspx page.

Anyways here's the code.
Unzip it and create a VD in IIS called FormsAuthenticationDemo2003 and point it at the FormsAuthenticationDemo2003 folder you just extracted.

That should be it.

I'll write you a quick manual security app. This uses base pages and requires a little bit more coding, but not much. We use this method at work.

Woka

RobDog888
Jul 13th, 2005, 03:59 PM
Thanks Badger, but I can keep unauthenticated viewers from viewing certain pages?

Wokawidget
Jul 13th, 2005, 04:44 PM
Yea...try and view the Users.aspx page without loggin in.
Try adding more pages to your project. WebForm1,2,3...blah.
Now run your project. They are ALL protected from users who are not logged in.
If you want a page to be viewed by someone who is not logged in then you need to add that page to the config file like I did with Users.aspx

It blocks all pages unless you explicitly state otherwsie.

Woof

Wokawidget
Jul 13th, 2005, 05:05 PM
OK, here's my 2nd demo. This uses custom authentication, so I leave the default web.config file as it is.

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:

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:

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:

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:

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
Jul 13th, 2005, 05:25 PM
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:

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

RobDog888
Jul 13th, 2005, 05:26 PM
Thanks allot Badger. This should keep me busy for another 4 months :lol:

Wokawidget
Jul 13th, 2005, 06:15 PM
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:

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:

'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:

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

RobDog888
Jul 13th, 2005, 06:23 PM
Thanks Badger. I got the latest and greatest now so I will go over both of them tonight from home.
I'll post more questions as this is allot to take in for an ASP.NET n00b like me. :lol:

Ruff! :thumb:

Wokawidget
Jul 13th, 2005, 07:03 PM
Here's the next installment :)

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

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 :(

Attached is the new updated project.

Wooof

Wokawidget
Jul 13th, 2005, 08:06 PM
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:

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:

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:

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

RobDog888
Jul 13th, 2005, 08:20 PM
Just finished dinner Badger. I see you have been busy again :thumb: I am checking it out now. ;)

RobDog888
Jul 13th, 2005, 08:26 PM
Booooo! *SLAP*

Error on the users page in the custom authentication sln:

RobDog888
Jul 13th, 2005, 10:49 PM
Fixed it so now on to the new part. :)

RobDog888
Jul 14th, 2005, 12:41 PM
Hey BadgerBoy, I got the original code working and wanted to know if I could merge the two logics together? Authenticate via
Windows and then use either cookies or a session variable to allow the user to view certain pages? Would the cookie logic be less
secure? I think it may be but I want your opinion.

If we were to use session vars is that also secure enough or what would I have to do?

Wokawidget
Jul 14th, 2005, 02:52 PM
Session varibles are more secure as the client has no access to them.
But cookies can be encrypted so they are secure.
At work we store a simple UID in the cookie, and validate this against a table in a DB.
Table is something like:


GUID
UserID
LastActiveDate

So you query the table for the row with the GUID, then validate the last active to see if they ain't timed out.
Alternatively you can encrypt the data in a cookie.
I like the idea of cookies.

I am not sure if you can merge the 2 authentication methods together :(
U may be able to validate a users domian login with some funky system namespace or some APIs.

I'll look into this for you.

woof

Wokawidget
Jul 14th, 2005, 02:52 PM
since you would use the same code as in my last example...all you need to do is fine ANY .NET code that can validate a users domian login. I know there are API's in VB6...so there must be something in .NET

Woof

RobDog888
Jul 14th, 2005, 05:23 PM
Actually the original code I posted is working for me somehow now. So thats why I was thinking that if they validate I can
create a session var of LoggedIn or something and have it timeout after 15 mins. Then when they navigate between pages it will
not need to validate to the db with another call but only verify the session var.

Does this sound like good logic?

Wokawidget
Jul 14th, 2005, 05:48 PM
Could you not use the impersonateValidUser function inside my validate function?

My code does not make a call to the DB, but our app at work does because we cannot use cookies, when you refresh a page. Well it does, but only the 1st time, then it creates a session var and a cookie. Just like yours will only validate the users Windows login.
Just replace MY DB code in ValidateUser, I think that's what I called the function, with code from your original post, mainly the impersonateValidUser function.

Make sense?

Going bed now...zzzzzzzzzz

Woof

RobDog888
Jul 14th, 2005, 05:58 PM
Yes, its starting to sink in, but only a shallow transversal. :(

I dont know how to use session vars only that they do exist. :) I'll take a crack at it tonight when I get home. If I get it I will post an update.

Thanks and it looks like your Badger is frollicking in the snow now. ;)

Anjari
Jul 15th, 2005, 12:15 AM
Where were you 3 months ago WOK... You need to turn this into a tutorial - I looked all over the net for answers you gave in this post... matter of fact I tried learning asp.net a year ago but the lack of your example like this ran me screaming back to asp.

Good Job, Bravo...

Anjari

RobDog888
Jul 15th, 2005, 12:20 AM
Yes the Badger is a lifesaver :thumb:

Sorry BadgerBoy I didnt finish it. Just thought I would let you know since I'm going to bed and your just waking up :.

Wokawidget
Jul 15th, 2005, 05:17 AM
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:

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:

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:

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
Jul 15th, 2005, 05:21 AM
Where were you 3 months ago WOK... You need to turn this into a tutorial - I looked all over the net for answers you gave in this post... matter of fact I tried learning asp.net a year ago but the lack of your example like this ran me screaming back to asp.

Good Job, Bravo...

Anjari
Thanks very much :blush:

:D

I was the same about a year ago...came looked around, couldn't find anything...gave up :(
The thing is that it doesn't take long to knock up a small example like this. More people should do it.

Woof

Wokawidget
Jul 15th, 2005, 08:37 AM
Thanks to Alex_Read and Matt3011 for there help with this.
For authenticating a login against an active directory you can use:

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

RobDog888
Jul 15th, 2005, 10:07 AM
Possibly, since I may want to do some custom stuff with Exchange and Outlook. I will need the users to be authenticated before
they get to that point and I will also be taking this info and using it to retrieve the Exchange data. ;)

Thanks for the updates! :thumb: We are running AD here and I am running it at home too so its all good. :D

Best not to do windows authentication for security reasons?

Wokawidget
Jul 15th, 2005, 10:12 AM
Best not to do windows authentication for security reasons?
Errrr....why? :confused:

I think you can still communicate with exchange etc even if you are not impersonating a windows user. So long as you have the domain, username and password you should be fine.

Woof

RobDog888
Jul 15th, 2005, 10:18 AM
Basically I mean would the code be opening vulnerabilities being on the web for hackers being able to sniff out the username/password?

RobDog888
Jul 15th, 2005, 10:21 AM
I do like the option of changing login validation methods ;) :thumb:

Wokawidget
Jul 15th, 2005, 10:22 AM
errr.nope. They could theoretically brute force it...but you can do that with any type of user authentication...DB, Hard coded etc.

My code above is ONLY validating that a username exists with that password. That's all it's doing.

Woka

Wokawidget
Jul 15th, 2005, 10:23 AM
I do like the option of changing login validation methods ;) :thumb:
Only for demo purposes...:D

Woka

RobDog888
Jul 15th, 2005, 10:34 AM
You mean the AD code? The original thread code was authenticating the actual windows authentication though,
or is it simulating the same?

Wokawidget
Jul 15th, 2005, 11:03 AM
The orginaly code was impersonating a windows user.
When you log into your web site IIS gives the active directory a windows username to use...in my case it's IUSR_BENDER for some reason, normall it's ASPUSR_COMPUTERNAME...this account gets installed and setup when you install IIS.
SO, say ISR_BENDER does not have permissions to access C:\Woof, any call to this dir in my code would result in a permissions error.
However, the user Admin, DOES have access to this. The original code you posted impersonates this user, which allows you to access C:\Woof. Make sense?

In the latest example I posted with code that validates against the Active Directory, function name ValidateActiveDirectoryLogin, this does not impersonate any user, so the user ISR_BENDER will be the windows account used when accessing resources on the server PC. The code I last posted ONLY validates if the domain, username and password exist.

To se what user the virtual directory is using...open up IIS...go to a VD properties.
Click on Directory Security tab...then click edit.

Personally I haven't come across a situation where I would want to impersonate a user.

Make sense?

WOka

RobDog888
Jul 15th, 2005, 11:06 AM
Starting to. The IUSR_BENDER username comes from your machine name, I believe, so your system is named BENDER ?

Wokawidget
Jul 15th, 2005, 11:14 AM
Yup...all my PCs on my Domain are named after characters from Futurama :D

Woka

RobDog888
Jul 15th, 2005, 11:30 AM
Our network admin has a thing for the new movie Dukes of Hazzard. :)
We have been upgrading and optimizing our network and
servers so they all are getting renamed. :lol:

Wokawidget
Jul 15th, 2005, 05:34 PM
OK. This one works.
This now encrypts the username into the cookie for a little extra protection.

I'm working on creating a security cookie class to make all that a little easier.

WOka

RobDog888
Jul 15th, 2005, 05:36 PM
Thanks BadgerBoy. :thumb:

I'll check it out tonight when I get home. Getting ready to leave soon. ;)

RobDog888
Jul 15th, 2005, 05:39 PM
Quick question BadgerBoy:

Instead of the username what if it encrypted some kind of serial number key that is generated upon the successful login in? Each time you
log in it generates a different #. This way its more secure and they wouldnt be able to get the username since it not being stored?

RobDog888
Jul 15th, 2005, 06:01 PM
Ok, then.

Since the Users page inherits from the MyBasePage does that mean that all pages that inherit it will carry over the authentication or
security? So if I had other pages that I didnt need to be secure then they wouldnt inherit the MyBasePage and the ones that I
need secure would?


BadgerBoy Jr. in training. ;)

Wokawidget
Jul 15th, 2005, 06:46 PM
yup. spot on...or you can inhgerit it as it may use the query string function, but just don't call ValidateLogin in page load.

RobDog888
Jul 15th, 2005, 10:08 PM
but just don't call ValidateLogin in page load.Darn, just when I started to get it you throw that at me. Why not in page_load? Dont you want to validate upon page load?


Edit: Nevermind, I just realized its from the button click. Doh! Too many posts today. :(

Wokawidget
Jul 16th, 2005, 06:16 AM
eh? Validate Login should not be from the button click.
If you want a page to be ONLY viewed by logged in users then call MyBase.ValidateLogin(True) in Page_Load.

If you want do show different things on the page, but still show it to not logged in users then call call the following in Page_Load

If MyBase.ValidateLogin(False) Then
'Show controls for login in users
Else
'Show controls for not logged in users
End If

If you don't call this function in pgae_load then the page will load normally for logged in and not logged in users.

Woof

RobDog888
Jul 16th, 2005, 09:29 AM
Ok, will do. I have to do allot of work today, at home, but hopefully I will have some time tofinish at least a few pages.
Functionality speaking anaways. Graphically is another story :(

RobDog888
Jul 26th, 2005, 05:47 PM
Just adding a good link from MS in case anyone wants more or other info. ;)

http://support.microsoft.com/default.aspx?scid=kb;en-us;315736