Click here to Skip to main content
15,175,834 members
Articles / Web Development / ASP.NET
Posted 21 Apr 2006


120 bookmarked

Form authentication and authorization in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.31/5 (55 votes)
21 Apr 20064 min read
This article will explain how to secure websites using the ASP.NET Forms Authentication.


As secure information is the key to efficient web programming, web application programmers always have security concerns. This article will explain how to secure your website using ASP.NET Form Authentication.

This article assume that the reader is already familiar with ASP.NET programming.


  • web.config: Application configuration files contain settings specific to an application. This file contains the configuration settings that the common language runtime reads (such as the assembly binding policy, remoting objects, and so on), and settings that the application can read [MSDN].
  • Authorization: The purpose of authorization is to determine whether an identity should be granted the requested type of access to a given resource [MSDN].
  • Authentication: Authentication is the process of discovering and verifying the identity of a principal, by examining the user's credentials and validating those credentials against some authority. The information obtained during authentication is directly usable by your code. That is, once the identity of the principal is discovered, you can use the .NET Framework role-based security to determine whether to allow that principal to access your code [MSDN].


I’ve searched so many sites for a code that I can with the help of it, secure websites from unauthorized access. After searching C# books, I found some nice code that helped me to create this simple application. Hope it can help as a basic architecture.

There are three kinds of authentication in ASP.NET:

  1. Form,
  2. Windows, and
  3. Passport.

This article will focus on the first type.

Form authentication is cookie based, as ASP.NET places a cookie in the client machine in order to track the user. If the user requests a secure page and has not logged in, then ASP.NET redirects him/her to the login page. Once the user is authenticated, he/she will be allowed to access the requested page.

Using the code

In the web.config, change the mode of authentication to Forms, then add loginUrl="your default page".

In this section, you will set the default page of the system. The default page is the page that the system will redirect the user to, whenever a fault happens while the user tries to access a secured page.

      This section sets the authentication policies
      of the application. Possible modes are "Windows", 
      "Forms", "Passport" and "None"

      "None" No authentication is performed. 
      "Windows" IIS performs authentication (Basic,
       Digest, or Integrated Windows) according to 
      its settings for the application.
      Anonymous access must be disabled in IIS. 
      "Forms" You provide a custom form (Web page)
      for users to enter their credentials, and then 
      you authenticate them in your application.
      A user credential token is stored in a cookie.
      "Passport" Authentication is performed via
      a centralized authentication service provided
      by Microsoft that offers a single logon 
      and core profile services for member sites.
    <authentication mode="Forms">
  <forms loginUrl="Login.aspx">

This section of the web.config determines the users who will be authorized to or denied from the website. The default value <deny users="?" /> means to deny any anonymous (unauthenticated) user trying to access the website. However, this value can be changed. E.g., <deny users="john”, “smith”, “Ahmed” /> means to deny the users: john, smith and Ahmed from accessing this website - it is a black list- or you can say <deny users="*" /> <allow users="john”, “smith”, “Ahmed” /> which means, deny all users except john, smith, and Ahmed.

    This section sets the authorization policies
    of the application. You can allow or deny access
    to application resources by user or role.
    Wildcards: "*" mean everyone, "?" means anonymous 
    (unauthenticated) users.


  <deny users="?" /> <!-- Allow all users -->
    <!--  <allow users="[comma separated list of users]"
                 roles="[comma separated list of roles]"/>
        <deny users="[comma separated list of users]"
              roles="[comma separated list of roles]"/>


In some business websites, multiple employees would need access to a system in order to do specific tasks. However, each employee would have a specific role, and specific operations to do, according to the nature of his/her job or security level. E.g., an HR manager might not allowed to view the data of the seals department.

ASP.NET provides the concept of roles that gives each role a different view on specific pages.

<location path="HRpages">
      <allow roles="HR" />
      <deny users="*" />

<location path="salesPages">
      <allow roles="sales" />
      <deny users="*" />

location here means the folder name which holds the .aspx for some specific role. As the example shows, <location path="HRpages"> means that all .aspx files under the HRpages folder are protected. <allow roles="HR" /><deny users="*" /> mean deny every one from accessing pages under HRpages except those having the HR role.


This section will show the code that reads the password and the user name from login.aspx and redirects the user to a specific page according to his/her role.

private void Submit1_Click (object sender, System.EventArgs e)
    if(this.TextBox_username.Text.Trim()== "HR_manager" 
        && this.TextBox_password.Text.Trim() == "password")     
         // Success, create non-persistent authentication cookie.
                 this.TextBox_username.Text.Trim(), flase);
         FormsAuthenticationTicket ticket1 = 
            new FormsAuthenticationTicket(
                 1,                                   // version
                 this.TextBox_username.Text.Trim(),   // get username  from the form
                 DateTime.Now,                        // issue time is now
                 DateTime.Now.AddMinutes(10),         // expires in 10 minutes
                 false,      // cookie is not persistent
                 "HR"                              // role assignment is stored
                 // in userData
          HttpCookie cookie1 = new HttpCookie(
            FormsAuthentication.Encrypt(ticket1) );

          // 4. Do the redirect. 
          String returnUrl1;
                 // the login is successful
          if (Request.QueryString["ReturnUrl"] == null)
              returnUrl1 = "HRpages/HR_main.aspx";
          //login not unsuccessful 
              returnUrl1 = Request.QueryString["ReturnUrl"];

The object ticket1 is of type FormsAuthenticationTicket and provides a means of creating and reading the values of a forms authentication cookie. The previous code will redirect the user HR_manager after checking his/her password. If the password is correct then it will create a cookie to track the user and encrypt the content of this cookie.

One of the FormsAuthenticationTicket constructors takes the following parameters:

  • version - the version number.
  • name - the user name associated with the ticket.
  • issueDate - the time at which the cookie was issued.
  • expiration - the expiration date for the cookie.
  • isPersistent - true if the cookie is persistent; otherwise, false.
  • userData - user-defined data to be stored in the cookie [MSDN].

Related tutorials


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Ahmed jamil Kattan
Web Developer
United Kingdom United Kingdom
Ahmed J. Kattan Bachelor degree from Jordan University of Science and Technology computer science department, Master Degree from University of Essex and PhD student at University of Essex ”United Kingdom”, I have written several applications, designed multiple algorithms and several publications. My favorite languages are C++ and C#.

see to view Ahmed Kattan's online CV.

Comments and Discussions

QuestionMessage Closed Pin
16-Nov-21 11:53
MemberSap ReEn16-Nov-21 11:53 
QuestionForms Credentials And Cookies Pin
Arif H Shigri1-Feb-15 6:09
MemberArif H Shigri1-Feb-15 6:09 
GeneralGood Article Pin
pandu0411-Mar-14 20:19
Memberpandu0411-Mar-14 20:19 
Question-- Pin
sandeepkmr88419-Nov-13 4:31
Membersandeepkmr88419-Nov-13 4:31 
GeneralMy vote of 1 Pin
nagaraju@techacesoft28-Mar-13 3:12
Membernagaraju@techacesoft28-Mar-13 3:12 
GeneralMy vote of 5 Pin
venchy24-Jan-13 1:24
Membervenchy24-Jan-13 1:24 
GeneralMy vote of 5 Pin
Pradeep Kumar Myakala30-Dec-12 3:23
MemberPradeep Kumar Myakala30-Dec-12 3:23 
QuestionGood Aritcle Pin
eng.ayman0111-Sep-12 12:18
Membereng.ayman0111-Sep-12 12:18 
GeneralMy vote of 2 Pin
a.anvesh3-Jul-12 3:07
Membera.anvesh3-Jul-12 3:07 
lot of
GeneralMy vote of 5 Pin
M.Hussain.28-Jun-12 0:53
MemberM.Hussain.28-Jun-12 0:53 
Questionprotection to files and folders Pin
mayur csharp G23-May-12 23:03
Membermayur csharp G23-May-12 23:03 
QuestionForm Authentication Pin
awadhendra tiwari27-Aug-11 6:34
Memberawadhendra tiwari27-Aug-11 6:34 
QuestionUse for a single Page? [modified] Pin
Member 815193510-Aug-11 13:52
MemberMember 815193510-Aug-11 13:52 
SuggestionRe: Use for a single Page? [modified] Pin
WebMaster9-Aug-12 9:09
MemberWebMaster9-Aug-12 9:09 
Generallogon using persistent cookies Pin
osman sonic8-Jan-11 10:13
Memberosman sonic8-Jan-11 10:13 
GeneralMy vote of 5 Pin
ayub55520-Aug-10 12:53
Memberayub55520-Aug-10 12:53 
Questionroles- how? Pin
ahmet.keskin12-Jun-09 4:46
Memberahmet.keskin12-Jun-09 4:46 
Questionwhat is the value of string returnurl and from where is comes Pin
anujbanka178411-Feb-09 21:53
Memberanujbanka178411-Feb-09 21:53 
AnswerRe: what is the value of string returnurl and from where is comes Pin
ahmet.keskin12-Jun-09 4:55
Memberahmet.keskin12-Jun-09 4:55 
GeneralRe: what is the value of string returnurl and from where is comes Pin
Sir PuruSh3-Jul-15 22:22
MemberSir PuruSh3-Jul-15 22:22 
GeneralThanks Pin
jortizromo11-Feb-09 7:47
Memberjortizromo11-Feb-09 7:47 
GeneralFormAuthentication / Authorization Roles... Pin
Anon123456789021-Dec-08 19:07
MemberAnon123456789021-Dec-08 19:07 
Generalrole assignement Pin
Member 269927031-Aug-08 12:10
MemberMember 269927031-Aug-08 12:10 
GeneralThanks Pin
EvilInside28-Apr-08 1:39
MemberEvilInside28-Apr-08 1:39 
QuestionRole assignment? Pin
udaysinhp2-Oct-07 23:05
Memberudaysinhp2-Oct-07 23:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.