Click here to Skip to main content
Click here to Skip to main content

Form authentication and authorization in ASP.NET

By , 21 Apr 2006
 

Introduction

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.

Keywords

  • 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].

Background

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.

<!--  AUTHENTICATION 
      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">
  </forms>
  
</authentication>

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.

<!--  AUTHORIZATION 
    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.
-->

<authorization>

  <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]"/>
    -->
</authorization>

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">
  <system.web> 
    <authorization>
      <allow roles="HR" />
      <deny users="*" />
    </authorization>
   </system.web>
</location>

<location path="salesPages">
  <system.web> 
    <authorization>
      <allow roles="sales" />
      <deny users="*" />
    </authorization>
   </system.web>
</location>

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.

Login.aspx.cs

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.
         FormsAuthentication.SetAuthCookie(
                 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.FormsCookieName, 
            FormsAuthentication.Encrypt(ticket1) );
          Response.Cookies.Add(cookie1);

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

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

License

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
Member
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 www.ahmedkattan.com to view Ahmed Kattan's online CV.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1membernagaraju@techacesoft28 Mar '13 - 2:12 
----
GeneralMy vote of 5membervenchy24 Jan '13 - 0:24 
nice
GeneralMy vote of 5memberpradeepkumar.myakala30 Dec '12 - 2:23 
guddd
QuestionGood Aritclemembereng.ayman0111 Sep '12 - 11:18 
Thabks for this great article!
QuestionThis can be done using ASP.net Configuration ToolmemberProgramminfree9 Aug '12 - 8:13 
Use ASP.NET Configuration tool to accomplish forms authentication which will do all the configuration coding for you at the background. It is very simple and explained here.
GeneralMy vote of 2membera.anvesh3 Jul '12 - 2:07 
lot of
GeneralMy vote of 5memberMuhammad Hussain Tabassum27 Jun '12 - 23:53 
Excellent and very concise and concrete information. Thanks brother.
Questionprotection to files and foldersmembermayur csharp G23 May '12 - 22:03 
How can we protect files like .doc,.pdf from protected folder to be viewed or download from url
QuestionForm Authenticationmemberawadhendra tiwari27 Aug '11 - 5:34 
Check this blog:
http://www.mindstick.com/Blog/177/Authentication%20and%20Authorization%20in%20ASP%20NET[^]
QuestionUse for a single Page? [modified]memberMember 815193510 Aug '11 - 12:52 
Is there a way to use this to protect a single page?
 
I used this and it protects every page on my website.
 
So anytime anyone goes to my webpage it directs them to my login...
 
I am only wanting it to redirect to login page if a user trys to view a protected page. And I am only trying to protect one page... not all of them. I have a feeling it is my web.config file. If I place it in the subdirectory I get a forms error... if i put it in the root folder, it blocks all pages till a user logs in.

modified on Wednesday, August 10, 2011 9:18 PM

SuggestionRe: Use for a single Page? [modified]memberProgramminfree9 Aug '12 - 8:09 
It is very simple. Just create a separate folder for pages you want to secure. Create a Web.Config file in that folder, and write appropriate authentication code. For example if you have a page Secured.aspx to be secured, then in the folder specific Web.Config file place the below code and now the system will authenticate only this web page while all others will be left unsecured. Hope this helps.
 
< system.web >
< authorization >
< deny users = "?" />
</ authorization >
</ system.web >

Generallogon using persistent cookiesmemberosman sonic8 Jan '11 - 9:13 
how to logon again without username and password using persistent cookies
GeneralMy vote of 5memberayub55520 Aug '10 - 11:53 
Very good for understanding in simple not complexity, everything is clear, thanks ahamed, please keep posting like this for us, allah aap ku khush rakhe
Questionroles- how?memberahmet.keskin12 Jun '09 - 3:46 
Hi, thanks for the article
I dont understand how .net knows that we store user roles in 'userdata' part of the ticket. We should create our own custom provider or what?
Questionwhat is the value of string returnurl and from where is comesmemberanujbanka178411 Feb '09 - 20:53 
what is the value of string returnurl and from where is comes ...
AnswerRe: what is the value of string returnurl and from where is comesmemberahmet.keskin12 Jun '09 - 3:55 
when you add these lines to your web.config file, .net assiigns return url automatically
 

<forms loginUrl="login.aspx" path="/" timeout="15">
</forms>

GeneralThanksmemberjortizromo11 Feb '09 - 6:47 
Smile | :) Excellent article, thanks a lot!! Smile | :)
GeneralFormAuthentication / Authorization Roles...memberDGDev21 Dec '08 - 18:07 
Am I mistaken, or does <allow roles=""/> only work with Windows Authentication.
I was having problems with this, and came across several sites which state so.
 
I'm looking into writing an extended custom UrlAuthorizationModule which allows a new xml attribute to be set to work with FormsAuthentication. Has anyone any knowledge on this?
 
I've created HttpModules before, but not sure if this is the best way to go about this.
 
DGDev
Generalrole assignementmemberMember 269927031 Aug '08 - 11:10 
The code was not runnig for me then I added a global.asax with the following code:
 
protected void Application_AuthenticateRequest(Object sender,EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
 
// Get the stored user-data, in this case, our roles
 
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
 
and now it's ok.
 
(I finded it on this article: http://www.codeproject.com/KB/web-security/formsroleauth.aspx[^]
GeneralThanksmemberEvilInside28 Apr '08 - 0:39 
I am novice to asp.net programming and I have googleing more than two days form custom authentication and authorization for my pages rather than using windows authorization tool, I found here what i need.
 
May it helps me..............
Smile | :)
Thak you
QuestionRole assignment?memberudaysinhp2 Oct '07 - 22:05 
Ho the role is assigned to perticular user? In this case how it is evaluated that user "HR_manager" belogns to role "HR" and allowd access to HRPages?
 
Udaysinh Patil
AnswerRe: Role assignment?memberAhmed jamil Kattan3 Oct '07 - 2:13 
Each role assigned to a page,and each page belongs to a folder.
 

such as:
 
<location path="HRpages">   // FOLDER NAME
   <system.web>
      <authorization>
         <allow roles="HR" />   //ROLE NAME
         <deny users="*" />
      </authorization>
   </system.web>
</location>
 

So HR role can access HRpages folder
 
// 4. Do the redirect.
               String returnUrl1;
                        // the login is successful
               if (Request.QueryString["ReturnUrl"] == null)
               {
                     returnUrl1 = "HRpages/HR_main.aspx";
               }
           
               //login not unsuccessful
               else
               {
                     returnUrl1 = Request.QueryString["ReturnUrl"];
               }
               Response.Redirect(returnUrl1);
      }
QuestionRe: Role assignment?memberudaysinhp3 Oct '07 - 18:48 
Thanks for you reply Ahmed. I hev two questions
 
1. You said "Each role assigned to a page". Are we doing this using any code or just in web.config like
// FOLDER NAME


//ROLE NAME




 
2. If I loging to system with username "xyz" then how system identifies that user "xyz" is HR person and allows it access? Is "xyz"<-->"HR" relationship defined somewhere?
 
Plese correct me if I am going in wrong direction.
 
Thanks
Uday

GeneralRe: Role assignment?memberGCpwell18 Feb '08 - 17:39 
Id like to know the answer to this too?? Is there any way to programmatically get the role that is assigned to the location (path) in the web.config?
Generalnice articlememberViragJ12 Sep '07 - 0:00 
nice article

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 21 Apr 2006
Article Copyright 2006 by Ahmed jamil Kattan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid