ASP.NET Forms Authentication - Part 1
by Abel Banda01/06/2003
Introduction
Often, in legacy Web applications, users authenticate themselves via a Web form. This Web form submits the user's credentials to business logic that determines their authorization level. Upon successful authentication, the application then submits a ticket in the form of a cookie, albeit a hard cookie or session variable. This ticket contains anything from just a valid session identification access token to customized personalization values.
ASP.NET encompasses and extends the very same logic described above into its architecture as an authentication facility, Forms Authentication. Forms Authentication is one of three authentication providers. Windows Authentication and Passport Authentication make up the other two providers. In this article, we will focus on 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 (e.g. therefore making the identity persistent). In essence, Forms Authentication is a means for wrapping your Web application around your own login user interface and verification processes.
|
Related Reading
.NET Windows Forms in a Nutshell |
Forms Authentication Flow
- A client generates a request for a protected resource (e.g. a secured page from your site).
- IIS (Internet Information Server) receives the request. If the requesting client is authenticated by IIS, the user/client is passed on to the ASP.NET application. Note that if Anonymous Access is enabled, the client will be passed onto the ASP.NET application by default. Otherwise, Windows will prompt the user for credentials to access the server's resources. Also note that because the authentication mode in the ASP.NET application is set to Forms, IIS authentication cannot be used.
- If the client doesn't contain a valid authentication ticket/cookie, ASP.NET will redirect the user to the URL specified in the loginURL attribute of the Authentication tag in your web.config file. This URL should contain the login page for your application. At this URL, the user is prompted to enter their credentials to gain access to the secure resource.
- The client must provide credentials, which are then authenticated/processed by your ASP.NET application. Your ASP.NET application also determines the authorization level of the request, and, if the client is authorized to access the secure resource, an authentication ticket is finally distributed to the client. If authentication fails, the client is usually returned an Access Denied message.
- The client can then be redirected back to the originally-requested resource, which is now accessible, provided that the client has met the authentication and authorization prerequisites discussed above. Once the authorization ticket/cookie is set, all subsequent requests will be authenticated automatically until the client closes the browser or the session terminates. You can have the user's credentials persist over time by setting the authorization ticket/cookie expiration value to the date you desire to have the credentials persist through. After that date, the user will have to log in again.
Setting Up Forms Authentication
Let's take a look at the applicable settings to execute Forms Authentication. In general, setting up Forms Authentication involves just a few simple steps.
- Enable anonymous access in IIS. By default, anonymous users should be allowed to access your Web application. In rare cases, however, you may opt to layer an Integrated Windows OS security layer level with Forms authentication. We will discuss how to integrate this layer with anonymous access enabled in the article succeeding this one ("Part 2 (Integration w/ Active Directory)").
- 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>Upon setting the
authentication modetoForms, you'll notice that we appended another child element. TheFormselement has five attributes that implement your forms authentication configuration. The attributes and their descriptions are as follows :Attribute Description nameThis is the name of the HTTP cookie from which we will store our authentication ticket and information, respectively. loginURLThis is the URL from which your unauthenticated client will be redirected. In most scenarios, this would be your login page, where the client is required to provide their credentials for authentication. protectionThis is used to set the method from which to protect your cookie data. The following valid values can be supplied:
All: Specifies to use both data validation and encryption to protect the cookie. Triple DES is used for encryption, if it is available and if the key is long enough (48 bytes). TheAllvalue is the default (and suggested) value.
None: Used for sites that are only using cookies for personalization and have weaker requirements for security. Both encryption and validation can be disabled. This is the most efficient performance wise, but must be used with caution.
Encryption: Specifies that the cookie is encrypted using Triple DES or DES, but data validation is not done on the cookie. It's important to note that this type of cookie is subject to chosen plaintext attacks.
Validation: Specifies to avoid encrypting the contents of the cookie, but validate that the cookie data has not been altered in transit. To create the cookie, the validation key is concatenated in a buffer with the cookie data and a MAC is computed/appended to the outgoing cookie.timeoutThis is the amount of time (in integer minutes) that the cookie has until it expires. The default value for this attribute is 30(thus expiring the cookie in 30 minutes).
The value specified is a sliding value, meaning that the cookie will expirenminutes from the time the last request was received.pathThis is the path to use for the issued cookie. The default value is set to " /" to avoid issues with mismatched case in paths. This is because browsers are case-sensitive when returning cookies.In our web.config file, it's also important to note the value we have for the
denychild element of theauthorizationsection (as highlighted below). Essentially, we set that value of theusersattribute to "?" to deny all anonymous users, thus redirecting unauthenticated clients to theloginURL.<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) { // authenticate user: this sample accepts only one user with // a name of username@domain.com and a password of 'password' if ((UserEmail.Value == "username@domain.com") && (UserPass.Value == "password")) { FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked); } else { lblResults.Text = "Invalid Credentials: Please try again"; } } </script> <body> <form runat="server"> <h3>Login Page</h3> <hr> Email:<input id="UserEmail" type="text" runat="server"/> <asp:RequiredFieldValidator ControlToValidate="UserEmail" Display="Static" ErrorMessage="*" runat="server"/> <p>Password:<input id="UserPass" type="password" runat="server"/> <asp:RequiredFieldValidator ControlToValidate="UserPass" 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. Upon clicking, the logic determines if the username and password provided match those hard-coded in the logic. If so, the client is redirected to the requested resource. If not, the client is not authorized, and thus receives a message depicting this.You can adjust the logic to fit your needs, as it is very likely that you will not have your usernames and passwords hard-coded into the logic. It is here at the
Login_Clickfunction that you can substitute the logic with that of your own. It is common practice to substitute database logic to verify the credentials against a data table with a stored procedure.You can also provide authorized credentials in the web.config file. Inside the forms section, you would append a user element(s), as follows :
<configuration> <system.web> <authentication mode="Forms"> <forms name=".COOKIEDEMO" loginUrl="login.aspx" protection="All" timeout="30" path="/"> <credentials passwordFormat="Clear"> <user name="user1" password="password1"/> <user name="user2" password="password2"/> <user name="user3" password="password3"/> </credentials> </forms> </authentication> <authorization> <deny users="?" /> </authorization> </system.web> </configuration>
cmdLogin button discussed above.
Here is the code :
void Login_Click(Object sender, EventArgs E)
{
// authenticate user: this sample authenticates
// against users in your app domain's web.config file
if (FormsAuthentication.Authenticate(UserEmail.Value,
UserPass.Value))
{
FormsAuthentication.RedirectFromLoginPage(UserEmail.Value,
PersistCookie.Checked);
}
else
{
lblResults.Text = "Invalid Credentials: Please try again";
}
}
Client Requirements
To enable forms authentication, cookies must be enabled on the client browser. If the client disables cookies, the cookie generated by Forms Authentication is lost and the client will not be able to authenticate.
Coming in Next Part of This Series
In the next part of this series, we'll discuss how to incorporate Active Directory with Forms Authentication, to get that Windows OS layer of security without forcing the user to authenticate twice, once through your user interface and again through the Windows user interface.
Return to ONDotnet.com
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 44 of 44.
-
which one is better
2007-01-24 16:22:49 boa_sovann [Reply | View]
hi all,
i know this is a strange question but i still want to ask all of you, programmers, that for web application do we should use session or form authentication or combine both of them? for the best
senario. could you please explain in details.
thanks in advance for your reply.
best regards
-
printing coding
2006-12-28 04:01:16 puducherry [Reply | View]
hello sir
i am working as a vb.net programmer. i konw the coding for create on text file and store the retrived records in that text file and print that file. now i want the formate in that text file. ie i want to splite the retrived record field. that is for example i retrived some records in this record one field is 100 character. i want to split that filed into 10 character per row.like that for each records.
-
Can we use multiple login form
2006-09-21 22:36:19 Sumit_Ranjan [Reply | View]
Hi,
I am using Form Authentication in my project. There are two folders: Admin and Guest. I want to use different login form for these folder. Means, I want to use adminLogin.aspx for Admin folder, and guestLogin.aspx for Guest folder. Can I use this? If yes, then what should be the configuration in Web.Config file? Please help me as soon as possible.
Thanks and regards
Sumit
sranjan@daaskonzern.com -
Can we use multiple login form
2007-01-21 16:50:36 boa_sovann [Reply | View]
hi all,
i am a new to asp.net web application developer and now working on a project which has a login page that restrict the users that store in my database table to login before they can access any other sites.
my web application directory is as follow:
solution/Book/Web.config
solution/Book/Admin/a.aspx
solution/Book/Admin/b.aspx
solution/Book/Operator/a.aspx
solution/Book/Operator/b.aspx
solution/Book/Guest/home.aspx
solution/Book/Guest/login.aspx
the default url is: .../Guest/home.aspx
and when the visitors click on login.aspx, then
enter thier user name and password and then click
on login. if the vaildation against database is correct, the users will redirect to the .../Admin/a.aspx, .../Operator/a.aspx as appropriate. so i need any helps to solve my problem.
thanks in advance for your help.
best regards
boa_sovann
-
Can we use multiple login form
2007-01-21 16:42:47 boa_sovann [Reply | View]
hi all,
i am a new to asp.net web application developer and now working on a project which has a login page that restrict the users that store in my database table to login before they can access any other sites.
my web application directory is as follow:
solution/Book/Web.config
.../Admin/
.../a.aspx
.../b.aspx
..........
.../Operator/
.../a.aspx
.../b.aspx
..........
.../Guest/
.../home.aspx
.../login.aspx
..........
the default url is: .../Guest/home.aspx
and when the visitors click on login.aspx, then
enter thier user name and password and then click
on login. if the vaildation against database is correct, the users will redirect to the .../Admin/a.aspx, .../Operator/a.aspx as appropriate. so i need any helps to solve my problem.
thanks in advance for your help.
best regards
boa_sovann
-
Can we use multiple login form
2006-10-08 05:45:03 manisha123 [Reply | View]
Hi,
I am using Form Authentication in my project. There are two folders: Admin and Guest. I want to use different login form for these folder. Means, I want to use adminLogin.aspx for Admin folder, and guestLogin.aspx for Guest folder. Can I use this? If yes, then what should be the configuration in Web.Config file? Please help me as soon as possible.
Thanks and regards
-
Can we use multiple login form
2006-10-04 20:43:18 jcmweb [Reply | View]
I believe that you can put seperate web.config files in each directory and set the authentication and authorization tags in the file to direct the users to the desired login pages. The web.config files are heirarchical in nature so if there is a web.config in the immediate directory it will overrule other ones.
-
forms authentication won't work
2004-06-18 09:43:19 petermonadjemi [Reply | View]
I have encoutered the stange phenomena that I sometimes can call webpages from a directory protected by forms authentication without having to be logged in. I am using WebMatrix have read that others have had the same problem but I haven't found a solution yet, here is my web.config:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".ASPXAUTH"
loginUrl="login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
Regards,
Peter Monadjemi -
forms authentication won't work
2006-11-20 20:47:00 kamalmca [Reply | View]
Hi Peter,
As per your Web.config code, you are not allowing anybody to enter into your site. However if you have any authenticated user by any means you may check that the cookie does not get created and also check that any Asp.NET instance should not be running when you run your application. These leads to similar kind of problems which you are facing.Let me know if it helps you.
-
Emergency-Form level authentication
2004-02-03 23:05:34 mohsen_ja [Reply | View]
hi.
I've faced with a problem in my .Net project.
I wanna use form level authentication but not for all forms of project. In the other words, when a certain form is called, I want to authenticate user to see whether he/she is allowed to access that form or not.
Thanks.
Kindly Regards,
Mohsen -
Emergency-Form level authentication
2004-06-03 09:02:25 WayneSO [Reply | View]
Mohsen,
I also need to allow access to all users on some pages in my applicaion while using forms authentication. Have you had any replies to your post or have you figured out how to do this?
Thanks,
Wayne -
Emergency-Form level authentication
2004-06-10 16:38:26 altanic [Reply | View]
look into the URLAuthorization stuff. I don't claim to have a solid handle on this but I've accomplished a working example on doing exactly what you guys ask for by setting each file/folder's authorization settings in the web.config file.
You would want to add an element such as:
<location path="PublicPage.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
for each item/folder you want to be freely available to everybody. Conversely, you could open your whole site to allow users="*" and then change the above to:
<location path="protected_directory">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
so as to protect this one directory. (or page if you like)
I think the key comes in understanding the <location> element and how it is used. Once you learn this you'll know enough.
-
Emergency-Form level authentication
2004-09-10 14:23:49 Bev3 [Reply | View]
Thanks ... I inherited a site that required an initial login ... as soon as the site was accessed, the first page was a login.aspx page.
It was later decided to have an open website with the previously secured information linked to from the default.aspx page.
Using the .Net 'Solution Explorer', I created a new subdirectory called "dbpages" and, again using the .Net 'Solution Explorer', I cut/pasted all of the original root directory pages and subdirectories into "dbpages".
After a lot of hair pulling / trying web.config files in subdirectories / wandering the web looking for a solution, I read this about <location> and tried it ... thanks much!
Previously, my root web.config was:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms name=".myCookie" loginUrl="./Login.aspx" protection="All" timeout="40" path="/"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
Now, my root web.config is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="dbpages/">
<system.web>
<authentication mode="Forms">
<forms name="./dbpages/myCookie" loginUrl="./dbpages/Login.aspx" protection="All" timeout="40" path="./dbpages/"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
</configuration>
I've left out a lot of <compilation> and <appSettings> as not pertinent to the discussion.
I also do not have/need any othe web.config than the one in the root directory ... thanks again!
-
Little problem
2004-01-30 04:52:52 hamid1 [Reply | View]
I am hoping that someone can help me with this. I created a login page and it worked wonderfully while I was in Visual Studio, however as soon as I try to access the page outside VS I keep getting redirected back to the login page. So I login, I am authenticated successfully, but as soon as I am redirected to the page I am trying toaccess it bounces me back to the login screen. Any help would be apreciated. -
Little problem
2004-04-05 12:49:43 chrisii [Reply | View]
I have the same problem.
I have two different servers and the problem only occurs on one of them. (which just happens to be my develoment system, not my producxtion system) Grrr...
Any ideas on how to fix that? I would think it would be a permissions issue but I don't have a clue where to start. (I've solved this problem in the past with a fresh install of windows, but that really isn't necessary.)
Any Help would be appreciated. -
Little problem
2004-07-16 10:30:37 oyster [Reply | View]
Hi,
I have the same problem, I tried with a simple application that just has to do with authentication (a default.aspx, login.aspx and web.config files). It works ok, but when tried with my "real" application, it does not work.
If someone has found the solution to this, plese let me know.
Thanks. -
Little problem
2004-04-27 15:23:44 chrisii [Reply | View]
I have figured out the problem to be cause by an Incorrect PATH Environment Variable. Which can be found in the System Control Panel.
"C:\Windows\Microsoft.NET\Framework\v1.1.4322" is the proper location to the current version of the .NET framework that I have installed.
-
Well Done
2004-01-06 10:22:57 anonymous2 [Reply | View]
I just wanted to add my kudos to the writer.
This article was exactly what I needed.
Thanks!!!!!!!!!!!!!!!!!
-
ASP.NET Forms Authentication
2003-11-26 12:33:14 sergeir [Reply | View]
Quick question...!
My network administrator has concerns regarding username and password values being entered on an .aspx page and then posted for forms authentication. His concern is that the actual values entered in the text boxes can somehow be sniffed as the page is posted to the server. I don not yet know enough about .NET or Internet explorer to support or dispute his claims of this being unsafe.
Nay help would be greatly appreciated...
-
ASP.NET Forms Authentication
2003-12-11 18:56:42 fleminga [Reply | View]
you need to place the login page into a directory which has https or ssl enabled -
ASP.NET Forms Authentication
2004-06-10 16:44:44 altanic [Reply | View]
^^ agreed. And your administrator has good reason to be concerned. The cookie will be resubmitted every time the user requests another protected page.
Check here for more info:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT16.asp
-
It's Perfect
2003-09-29 09:23:03 anonymous2 [Reply | View]
I'm from Turkiye. I buy a book for ASP.NET. ý make samples in book but not work. I find this sample. Its working now.
Thank You.
-
UserEmail
2003-09-16 13:40:43 anonymous2 [Reply | View]
What is UserEmail because its not working
even after I'd imports System.Web.Security
it's not compiling with that "UserEmail"
what is it???
-
Part 2 On Its Way!
2003-08-13 02:13:22 anonymous2 [Reply | View]
Can u give me guide to make a datagrid (include edit,delete and add function)using property builder?
-
time out
2003-06-26 21:04:52 anonymous2 [Reply | View]
i got the form working but i am using sessions, i want to redirect the user to loging again when the session expire, how can i sincronize that with the form authentication timeout
-
can not login in unsecured zone
2003-06-05 11:02:34 anonymous2 [Reply | View]
This article assumes the login page is in the secured portion of the website. What if there is an unsecured portion (main directory) and a secured portion (subdirectory)? I want the user to be able to input credentials in the login page contained in the public area. If authenticated from the database, the user is redirected to the private home page in the secured directory. -
can not login in unsecured zone
2006-02-19 03:30:44 Wiggy [Reply | View]
I had this same question, and I've now found the answer. In web.Config at the moment you will have something like:-
<system.web>
<authentication mode="Forms" >
<forms
name="MyApp"
path="/"
loginUrl="Logon.aspx"
protection="All"
timeout="20">
</forms>
</authentication>
</system.web>
You will need to add after the </system.web> something like this:-
<location path="Public">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
This will allow anyone (authorised or not authorised) to access the pages in the "Public" directory.
-
Clear
2003-05-29 20:08:45 anonymous2 [Reply | View]
This is like finding a needle in a haystack of information. Clear and lucid
-
Nice!
2003-04-03 21:25:12 anonymous2 [Reply | View]
Just got part II, this one's good too! you have a new fan.
~Andrew Curtis (New York)
-
Concise and to the point
2003-01-21 21:40:13 anonymous2 [Reply | View]
Very well written. Doesn't bring in extraneous details, yet doesn't leave the needed stuff out.
Thanks
-
Part 2 On Its Way!
2003-01-16 21:14:03 abelbanda.com [Reply | View]
Hey, thanks for reading my article! I'm glad you liked it! E-mail me if you have any questions, I'd be more than happy to help. The real challenge is true block impersonation! That's the fun one! I hope to write on that some day as I have the code generated for it already. Thanks again and happy coding!
--Abe (www.abelbanda.com)
-
When is Part 2 coming?!
2003-01-16 18:19:40 anonymous2 [Reply | View]
Part 1 is very thorough and helpful - O'Reilly comes through again! We're working on a project now for which the information promised in Part 2 - integrating Forms Authentication with Active Directory - would doubtless save us many hours of investigation. Can you publish it tomorrow?! The next day?! :-)










I am in the early phase of setting a security systme in mu dot net app. I am intereseted in any suggestion or feedback or tool about this