ASP.NET Forms Authentication, Part 2
by Abel Banda01/20/2003
Introduction
When you need to have an OS security level wrapped around your Web application in a legacy environment, you would switch your Web app's IIS setting for "Allow Anonymous User" off, thus enabling your Web application to execute without allowing anonymous users to access your Web application's resources. Doing this would prompt the user to enter their credentials. If your Web app had an application security layer, the user would be required to re-enter their credentials. Often, clients can find this redundant, but necessary for the security level that the business scope requires.
ASP.NET brought us Forms Authentication, which encompasses and extends the application security layer seen in most Web applications. We can extend Forms Authentication's functionality to authenticate against the Active Directory, hence adding an OS security level without the user having to provide their credentials multiple times. In this article, we'll discuss how to log in with Forms Authentication using an active account in Active Directory.
Forms Authentication
Forms Authentication is a system in which unauthenticated requests are redirected to a Web form where users are required to provide their credentials. Upon submitting the form, and being properly verified by your application, an authorization ticket is issued by your Web application, in the form of a cookie. This authorization cookie contains the user's credentials or a key for reacquiring the user's identity (therefore making the user's identity persistent). In essence, Forms Authentication is a means for wrapping your Web application with a thin security layer, allowing you to have your own custom login interface and verification functionality.
|
Related Reading
.NET Windows Forms in a Nutshell |
Active Directory
Active Directory is an essential and inseparable element of the Windows 2000 network architecture that lets organizations efficiently share and manage information about network resources and users. It's essentially a single point of management for Windows-based user accounts, clients, and applications. It also helps organizations integrate non-Windows application with Windows-based applications and devices, thus consolidating directories and easing management of the entire network operating system. Organizations also use Active Directory to extend systems securely to the Internet by forcing their Web application users to authenticate themselves against their single-point Active Directory.
Setting Up Forms Authentication with Active Directory
Let's take a look at the applicable settings to execute Forms Authentication with Active Directory. If you would like more details on Forms Authentication on general, please refer to Part 1 of this series, where all the settings, properties, attributes, and general code for a standard Forms Authentication setup are discussed in greater detail.
In general, setting up Forms Authentication involves just a few more simple steps than the average setup for a standard Forms Authentication Web site. The additional steps, of course, revolve around the the code logic to authenticate the user's credentials against Active Directory. Let's start by setting up a standard Forms Authentication!
- Enable anonymous access in IIS. By default, anonymous users should be allowed to access your Web application.
- Configure your Web application's
web.config file to use Forms Authentication.
Start by setting the authentication mode attribute to Forms,
and denying access to anonymous users. The following example shows how this
can be done in the web.config file for your Web application:
<configuration> <system.web> <authentication mode="Forms"> <forms name=".COOKIEDEMO" loginUrl="login.aspx" protection="All" timeout="30" path="/"/> </authentication> <authorization> <deny users="?" /> </authorization> </system.web> </configuration> -
Create your login page (as
referenced in the
loginURLattribute discussed above). In this case, we should save our login page as login.aspx. This is the page to where clients without valid authentication cookie will be redirected. The client will complete the HTML form and submit the values to the server. You can use the example below as a prototype.<%@ Import Namespace="System.Web.Security " %> <html> <script language="C#" runat=server> void Login_Click(Object sender, EventArgs E) { // we will append our authentication logic here next! } </script> <body> <form runat="server" ID="Form1"> <h3>Login Page</h3> <hr> UserName:<input id="UserName" type="text" runat="server"/> <asp:RequiredFieldValidator ControlToValidate="UserName" Display="Static" ErrorMessage="*" runat="server"/> <p>Password:<input id="UserPass" type="password" runat="server"/> <asp:RequiredFieldValidator ControlToValidate="UserPass" Display="Static" ErrorMessage="*" runat="server"/> <p>Domain:<input id="UserDomain" type="text" runat="server"/> <asp:RequiredFieldValidator ControlToValidate="UserDomain" Display="Static" ErrorMessage="*" runat="server"/> <p>Persistent Cookie:<ASP:CheckBox id="PersistCookie" runat="server" /> <p><asp:button id="cmdLogin" text="Login" OnClick="Login_Click" runat="server"/> <p><asp:Label id="lblResults" ForeColor="red" Font-Size="10" runat="server" /> </form> </body> </html>It's important to note that the above page authenticates the client on the click event of the
cmdLoginbutton. This will trigger theLogin_Clickfunction to execute. You can adjust the logic in this function to fit your needs. It is common practice to substitute database logic to verify the credentials against a data table with a stored procedure. It is here at theLogin_Clickfunction that we will insert the logic to authenticate against Active Directory. Before we work on the authentication logic, we must first import some new namespaces to have accessibility to advapi32.dll, which we will interact with through interop. The following namespaces must be accessed as follows:<%@ Import Namespace="System.Web.Security" %> <%@ Import Namespace="System.Runtime.InteropServices" %>Now the fun part! Let's alter the
<script>for our authentication run, as follows :<script language="C#" runat=server> [DllImport("advapi32.dll", CharSet=CharSet.Auto)] public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); public const int LOGON32_LOGON_INTERACTIVE = 2; public const int LOGON32_PROVIDER_DEFAULT = 0; void Login_Click(Object sender, EventArgs E) { IntPtr token = IntPtr.Zero; if(LogonUser(UserName.Value, UserDomain.Value, UserPass.Value, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { FormsAuthentication.RedirectFromLoginPage(UserName.Value, PersistCookie.Checked); } else { lblResults.Text = "Invalid Credentials: Please try again"; } } </script>The
<script>block above uses COM Interop provided by theSystem.Runtime.InteropServicesnamespace. This is necessary to interact with the advapi32.dll. This DLL is accessed from the[DllImport]call made at the top of the script block. We specify which method to access and the required parameters to send (this is also referred to as the method fingerprint).We declare a couple of constants by their variable names.
LOGON32_LOGON_INTERACTIVEis an integer representing the logon type we wish to execute andLOGON32_PROVIDER_DEFAULTspecifies the provider we wish to use. Now, let's look at theLogin_Clickfunction more closely.The first thing we do, right off the bat, is create a pointer,
token. We set it to "0" by default. It will be used to receive the results of the call toLogonUser. If it returns anything other than a "0" integer, then we we're successfully issued a valid user token, meaning that credentials were successfully authenticated.If the user's credentials were successfully authenticated, the user is redirected to the resource he/she tried to access, via the
FormsAuthentication.RedirectFromLoginPagecall. If not, an error message is displayed on the page via the setting of thetextproperty for thelblResultsobject.
Summary
Now that wasn't hard, was it? For so little code, it has huge implications and opens the gateway for possibilities in your next application. There are several reasons why companies utilize Active Directory. The primary reason, though, is to have a consolidated single point of user account control. Enabling your Web application to take advantage of interaction with Active Directory will allow you to prevent duplicate user account control systems and snap into an already established architecture already in effect. Good luck and see you next time!
Return to ONDotnet.com
Showing messages 1 through 26 of 26.
-
Mine of gold - If you still can only authenticate admin users
2007-04-12 09:44:23 ProGraMMer [View]
-
Handle to web page
2006-11-13 03:26:06 shaeron [View]
Can anybody tell me how can we gain handles of web page if we are developing an application in ASP.net
Basically i want a substitute of "Windows.form.handle as IntPtr " (which is used in desktop application) in ASP.net
Thanks
-
Great Article
2006-06-27 08:50:17 RWC_Chris [View]
Thanks, very easy to implement. Worked the first time!
-
Works Perfect. But...
2006-06-19 12:22:23 aRaminelli [View]
...Just wondering how to bring the Active Directory users to the web admin so I can setup roles!
Thanks for the code
-
get the DirectoryEntry root properties
2006-06-02 03:49:10 kotia [View]
nice code, worked perfectly with mine. I have downloaded some sample codes of AD Directory utilities, tried to get the OU name of the DirectoryEntry root from asp.net page (aspx), but always ended up server is not functioning.
With your code, I managed to logged in and get authenticated, but any idea how do i get the user object properties or the DirectoryEntry root?
I need it to pass the OU to the redirected page as a query string.
please help asap.
-
VB Version of this code.
2006-04-30 12:45:43 erolsensoy [View]
Thanks for simple and easy code. i'm take advantage this and working good. But i must use VB version of this code. i did translate to Vb version. May any visitors will take advantage.
Thanks.
// CODE STARTED HERE //
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Runtime.InteropServices" %>
<html>
<script language="VB" runat=server>
Declare Auto Function LogonUser 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 Integer) As Integer
Public Const LOGON32_LOGON_INTERACTIVE As Integer = 2
Public Const LOGON32_PROVIDER_DEFAULT As Integer = 0
Protected Sub Login_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim token As Integer
If (LogonUser(UserName.Value, _
UserDomain.Value, _
UserPass.Value, _
LOGON32_LOGON_INTERACTIVE, _
LOGON32_PROVIDER_DEFAULT, _
token) <> 0) Then
Session("useractive") = "active"
FormsAuthentication.RedirectFromLoginPage(UserName.Value, False)
Else
Session("useractive") = "notactive"
lblResults.Text = "Username and/or Password is wrong. Try Again."
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
UserName.Value = "MYUSERNAME" ' Not needed. require for only default value
UserDomain.Value = "MYDOMAIN" ' Not needed. require for only default value
End Sub
</script>
// CODE END HERE -
RE: VB Version of this code.
2006-07-25 07:02:12 AlohaMora [View]
Dear erolsensoy
I tried to use the VB code but it is not working, i did the steps as mentioned but all in vain. My Requirment is to open a login form as default page of the web application, user will pur username ppassword as in Active directory and it show be authanticated from AD database. and also i want to pick the user information like name phone address eamil etc from AD.
my email is itsrajiv@hotmail.com
plz send me ur i will send u the project and u can plz make changed for me.
thanks in advance i really need it working bec its my job requirment so plz help me
-
Simple and good
2006-03-07 18:59:30 jaseloh [View]
The code is simple and easy to understand, thanks for sharing
-
Great Code - Quick Question
2006-01-27 03:36:17 PhalanxX [View]
When the user is authenticated using this method are they still as far as the webser is concerned IUSER_WEB or are they now logged on using the credetials provided (i.e. domainname\username) ?
thanks
-
Force AD Login in asp.net from all pages.
2005-09-15 10:07:12 tward3017 [View]
Can some give me an example of how in asp.net I can force a user who attempts to browse a page to be directed to the AD Login page.
Example: http://sitename/login.aspx
User tries to get to http://sitename/subdir/page.aspx I need them to be redirected to the login page and maintain authentication to any page after successfully authentication other wise they constantly get the loginpage.aspx. -
Force AD Login in asp.net from all pages.
2005-09-19 23:24:41 najeemmillyas [View]
Hi,
You may set a session variable immediately after login success.Also you may chech the session set or not while a page is accessing.If session session not set then redirect the user to login page
Sample code
'login.aspx:
'after athentication success
session("sess_var")="36136jdasd"
'under page load event of protected page
if (Session("sess_var")="")
Response.redirect("login.aspx")
End if
place the above code in any page u need to protect.
Regards,
Najeem
http://www.najsoftindia.com
-
Great code but..
2005-06-07 14:00:43 gharryh [View]
Great code but how schould i proceed to make this form to be the first page that a users sees when he acceses the website
-
Windows 2003
2005-05-22 12:41:59 neb24usa [View]
Does this code work with Windows 2003? If not does anyone know a way to get forms to work with 2003 AD?
-
problem with web.config
2003-12-08 20:54:05 anonymous2 [View]
I saved codes above in a folder and then run login.aspx file in IIS with a error :
Access to the path "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files\aspnet\11f9c6d0\d8fd79cf\-z9cywco.0.cs" is denied.
I dont know why?. Anyone help me ?
-
always returns "Invalid credentials"
2003-08-18 07:30:33 anonymous2 [View]
Been trying out the script but always returns "invalid credentails". Im guessing there is some problem accessing the advapi32.dll, since the login i use works fine with windows authentication.
any thoughts?
-
Works great ... but
2003-04-12 08:54:13 anonymous2 [View]
I've run the ASP.NET Forms Authentication, Part 2
example, and it works as expected, but only when the user account (active directory) is a member of the "Administrators" group.
Naturally, I want to authenticate a member of "Domain Users" as well.
Any thoughts about what I'm doing wrong? -
Works great ... but
2003-04-28 22:28:28 anonymous2 [View]
uh ya, man, dude, nothing will work if priviledges prohibit them -- uh ya, for this to work, the executing account thread should have priviledges. if you protect a web site with authentication, and they don't hit it, do you call that a bug too? Geez... i thought it was good writing, but those are my props. [San Diego]
-
Is it really working? I dont think so!
2003-04-08 04:31:22 anonymous2 [View]
What about the failure of LogonUser() due to lack of privileges? -
Is it really working? I dont think so!
2003-04-28 22:24:49 anonymous2 [View]
Umm, dude, uhh, nothing will work if priviledges prohibit them -- uh ya.
-
Easy to read...
2003-04-03 21:22:22 anonymous2 [View]
finally this is in english...we're not all tech gurus! thanks for making life easier.
~Andrew Curtis
-
Excellent Job.
2003-03-27 17:04:17 anonymous2 [View]
I have been looking for something like this for a long time. Didnt know it was that easy. Thanks alot.
~Robert Rivera
-
Drag and Drop
2008-05-29 11:54:07 sanknm [View]
Hi,
Can any one help me i.e How to Drag the list items From one list box to another list box
with out using any buttions. -
Excellent Job.
2003-04-02 21:46:59 anonymous2 [View]
Very nice... This will do me lots of good ;)
-
Good Work!
2003-02-28 08:24:42 anonymous2 [View]
Wow! Seems like the last person on this thread was having a bad day! I read that and had to give you props on a well done article. Good Work!
-
Re: How Did You Figure This Out
2003-02-23 20:57:02 anonymous2 [View]
It's kind of pathetic to see the author or one of his friends post a stupid comment like this.
Yes, it's a cute article containing the same information available at (or 'adapted' from) more than a dozen different books or online articles already available.
Get a life.
-
How did you figure this out?
2003-02-20 07:35:40 anonymous2 [View]
Wow! This is some mean code. Great work -- and easy to understand. Another grand slam of an article. Glad to see O'Reilly picked you up!










If it works and you can only authenticate admin users:
1 - go to iis and enable impersonation for your login page using an admin account
2 - go to iis and make the process run this file using an admin account
3 - the most important: use #define LOGON32_LOGON_NETWORK 3 instead of 2
Good Luck Fellows