google analytics

Wednesday, November 5, 2008

ASP.NET Form Authentication

Hello All

Today I will demonstrate how to do Form based authentication manually.Though it can be maintained through login controls which is provided by Visual Studio but sometime we need to do the task without using those controls and the required database.

First we have to perform validation for the user, then we needed to authenticate the user for different type of task according to the role of the user ( I will do role based authentication.) In my example I have a folder named "Secure" which can be access only by the Admin user. (in the following code I assume that U have done the validation for a user.)

  /* we are taking expire time duration form application settings file you may also hard coded this value.*/
double EXPIRETIMELIMIT = Convert.ToDouble(ConfigurationManager.AppSettings["EXPIRETIMELIMIT"]);

  FormsAuthentication.Initialize();
  FormsAuthentication.HashPasswordForStoringInConfigFile("password", "md5");
            
  StringBuilder roles = newStringBuilder();
  /* bellow i have added 2 roles , you may add roles according to your logic.*/
  roles.Append("Admin");
  roles.Append("Manager");
               
  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "User Name", DateTime.Now, DateTime.Now.AddMinutes(EXPIRETIMELIMIT), true, roles.ToString(), FormsAuthentication.FormsCookiePath);         
  string hash = FormsAuthentication.Encrypt(ticket);      
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
/*We have to set the cookie expire time manually,its not working which we set in the parameter  of the FormsAuthenticationTicket's constructor .*/
 cookie.Expires = DateTime.Now.AddMinutes(EXPIRETIMELIMIT); 

 if(ticket.IsPersistent)
    cookie.Expires = ticket.Expiration;

 Response.Cookies.Add(cookie);

 Response.Redirect("Admin/Home.aspx");
Now open the the Global.asax file,if its not exist in your current solution add it as a new item. Then add the following code block as bellow,which will chek the authentication in each page request.
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 identity = (FormsIdentity)HttpContext.Current.User.Identity;

                   FormsAuthenticationTicket ticket = identity.Ticket;
//         UserData is the roles which we have assigned before.
                   string[] roles = ticket.UserData.Split(new Char[] {','});
                                     
                   HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
                   
               }            
           }        
       }    
   }
Now its the time to securing our folder from web.config  . When any Authorized user will try to access in the Admin folder then this will check the "Admin" role for the user.
<authentication mode="Forms">
        <forms name="MYWEBAPP.ASPXAUTH"  loginUrl="TeleMarketerLogin.aspx" protection="All" path="/"/>  
    </authentication>
    <authorization>
        <deny users="?"/>
        <allow roles="Manager,Admin"/>
        <deny users="*"/>
    </authorization>

<location path="Secure">
    <system.web>
        <authorization>
        <deny users="?"/>
        <allow roles="Admin"/>
        <deny users="*"/>
        </authorization>
    </system.web>
</location>

<location path="App_Themes">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>
thats all for today.
BYE
User ScrumPad for your Agile based projects.

2 comments:

  1. thanks a lot. i lived surprise when i see that App_Themes defines with out ~ (thilda).

    ReplyDelete
  2. Thanks for the demonstrations for doing form based authentication manually. I am also describing about the use of SHA1 for HMAC Generation and AES for Encryption: SHA1 is preferred to MD5 hashing because it produces a larger hash size; therefore, it is considered to be more secure. AES is preferred to DES and 3DES because of its larger key sizes. ASP.NET version 2.0 defaults to using SHA1 and AES. The following defaults are documented in the Machine.config.comments file.


    With the default values of Auto for the decryption attribute and Auto Generate, Isolate Apps for the decryption key, tickets are encrypted with AES symmetric encryption.

    ReplyDelete