Wednesday, December 2, 2015

FormsAuthentication in ASP.Net

First, you can read and find rich set of contents here. And going further, it is not that complex to implement and use FormsAuthentication in ASP.Net. For instance, look at the below login method which the FormsAuthentication is used if the user clicked on the "Remember Me" function.

 public void RememberAuthentication(ContextUtility context,string username)  
     {  
       Response.Cookies.Clear();  
       FormsAuthentication.Initialize();  
       FormsAuthentication.SetAuthCookie(EncryptionUtility.Encrypt(username), false);  
       FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(  
         1,                                     // ticket version  
         EncryptionUtility.Encrypt(username),                    // authenticated username  
         DateTime.Now,                                // issued date  
         DateTime.Now.AddDays(7),                          // expiry date  
         true,                                    // true to persist across browser sessions  
         EncryptionUtility.Encrypt(context.GetValueAsInt("idPerson").ToString()),  // can be used to store additional user data  
         FormsAuthentication.FormsCookiePath);                    // the path for the cookie  
       // Encrypt the ticket using the machine key  
       string encryptedTicket = FormsAuthentication.Encrypt(ticket);  
       // Add the cookie to the request to save it  
       HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);  
       cookie.HttpOnly = true;  
       Response.Cookies.Add(cookie);        
     }  

The context is an object containing user details such as usernam, id and many more. The encryption utility is a global method that is used to encrypt any given string. We will discuss the method in detail in the next post.

Lets see how the above "RememberAuthentication" method can be used in login implementation.

 private void Login()  
     {  
       ContextUtility context = new AdmLoginBLL().Login(txtUsername.Text.Trim(), txtPassword.Text.Trim(), ContextEntity);  
       if (cbRememberMe.Checked)  
         RememberAuthentication(context, txtUsername.Text.Trim());  
       if (context.GetValueAsInt("idPerson") > 0)  
         Response.Redirect("Home.aspx", false);  
     }  

The remember me option will make the user to be remembered if he comes back to the site after logged in. To do so, we need to validate the users identity at the page load event.

 if (Context.User.Identity.IsAuthenticated)  
         {  
           Response.Redirect("Home.aspx");  
         }  

Remember to validate Home page with the user logged in and you need to provide authorization as well.





No comments:

Post a Comment