Franc Stratton's .NET (TM) Web Application, OOP, and SOA Architecture & Programming Site

A site devoted to ASP.NET (TM), SilverLight (TM) and Browser-Based WPF (TM) Applications, IIS Services, and OOP Architectures

Home     Architecture Overview     WF/WCF/WPF     Data Store     Standards     .NET Security     Resources     jQuery     Silverlight     Developer Tips     Blog     Site Map      
Input validation
Authentication
Forms Authentication
Authorization
Configuration Mgt
Sensitive Data
Session Mgt
Cryptography
Parameters
Exception Mgt
Auditing/Logging
SQL Injection
Cross-site Scripting
String Validation
Authentication methodologies to help prevent attacks:

 

In the form login button click event for an ASP.NET Web application, the developer should limit the number of tries for a login to a pre-determined limit, and then lock out the user account in the database. The programmer should validate the user name and password at the client with JavaScript validators, and then validate a second time with server-side code business logic. Regular expressions are a common forms of both client-side and server-side validation methods. Limiting a user name or password textbox with the maximum limit property also will perform a type of string size validation. The login button click event might contain:

 

protected void btnSignin_Click(object sender, EventArgs e)

{

/// <summary>

/// Count number of login tries and could lockout if too many.

/// Clean both password and user id then compare to decrypted

/// password in login database. Stored login info in database.

/// If authenticated, then encrypt cookie for forms authentication.

/// Save cookie, and if times out, user must login again.

/// </summary>

numLoginTries = numLoginTries + 1;

if (numLoginTries >= 4)

{

    this.txtUserName.Text = "";

    this.txtPassword.Text = "";

    //put in code here to lock out user from logging into database again if needed.

    //put in code here to notify security web service of violation if applicable

    this.lblMessage.Text = "You have exceeded the number of allowable login tries. You are now locked out of this application.";

    return;

}//if (numLoginTries >= 4)

else

    {

         // Attempt to Authenticate User Credentials using encrypted passwords

         string passWord = string.Empty;

         //Clean the RacfID and Password strings before passing on

         string userId = CleanStringRegex(this.txtUserName.Text.Trim());

         string UserPassword = CleanStringRegex(this.txtPassword.Text.Trim());

         //validate clean strings for racfId and password character/number formats/allowable special characters

         if (ValidateUserAndPassword(userId, userPassword) == true)

         {

         //User name and password validated at Client and then Business Object

         //Now fetch encrypted password by RACFID, decrypt, and compare in

         //Business Object

         try

         {

         //Use a hash of the password with a salt value and compare hashes.

             userObject = Logon(userDS, userId, userPassword);

             //If results returned, then login valid

             if (userObject.IsValid == true)

                 {

                 //Login valid, so now make audit log login entry

                     if (MakeAuditLogEntry(userId.Trim()) == false)

                     {

                         this.lblMessage.Text = "Unable to log in, please try again later.";

                         return;

                     }

                    

                     //set up for cookie encryption

                     string encryptedTicket = "";

                     string userData = userId.Trim();

                     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

                              1,

                              userData.Trim(),

                              System.DateTime.Now,

                              System.DateTime.Now.AddMinutes(60),

                              false,

                                    userData,

                                    FormsAuthentication.FormsCookiePath);

                                encryptedTicket = FormsAuthentication.Encrypt(ticket);

                              // Use security system to set the UserID within a client-side Cookie

                              Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));

                     

                           //Read the coookie back from the client pc and compare user id to cookie user id

                          // We need to perform this check first, to avoid null exception

                          // if cookie does not exist

                          if (Request.Cookies[".cooknamefromwebconfig"] != null)

                          {

                              FormsAuthenticationTicket newTicket = null;

                              //cookie name is set in the web.config forms authentication section

                              newTicket = FormsAuthentication.Decrypt(Request.Cookies[".cooknamefromwebconfig"].Value);

                              string userDataString = newTicket.UserData.ToString();

                              if (userId.Trim()== userDataString) //If user id from decrypted cookie = user value before adding

                              {

                                  //Redirect browser to MainMenu.aspx

                                  FormsAuthentication.RedirectFromLoginPage(userRacfId.Trim(), false);

                              }

                            }

                          else

                          {

                           //if rows not returned, then login not valid, prompt with Login Failed

                               this.lblMessage.Text = userMessage.Trim() + "  <" + "br" + ">Login Failed!" + "<" + "br" + ">";

                          }

                    }   //try

                    catch (Exception g)

                    {

                        if (userMessage != "OK")

                        {

                            //In this application, user message inserted

                            //from business object, and real error goes to

                            //Exception handler Web or WCF Service

                            ShowMessageBox(this.Page, userMessage);

                            //ShowMessageBox is a JavaScript alert box

                        }

                        else

                        {

                            //put BLL save app error here.

                            string sError = ReturnBLLErrorDescription(g);

                            HandleBPAppErrors(1, "Client.Signin_Click", userRacfId.Trim(), sError);

                            userMessage = "An error has occurred and has been reported";

                            //ShowMessageBox is a JavaScript alert box

                            ShowMessageBox(this.Page, userMessage.Trim());

                            //You can also display error message on form label by uncommenting the code below

                            //this.lblError.Text = sError;

                        }

                    }

                }

            }// else if (numLoginTries >= 4)

 

 

In the form initialization and load events, use Forms Authentication and encrypted tickets in the cookie to prevent unauthorized access to forms before they query the database and present sensitive data to the client browser. For example, in the “Page_init” event, verify that the page request is from an authenticated user with code like the following:

 

// Check whether the current request has been

// authenticated. If it has not, redirect the

// user to the Login.aspx page.

if (!Request.IsAuthenticated)

{

    Response.Redirect("Login.aspx", false);

}

 

If it has not been authenticated, the request is redirected to a login page where users can enter their user name and password credentials into the Web application.

If you load JavaScript code from the “Page_init” event of an ASP.NET form, further security can be assured by first checking to see if the user has been authenticated:

 

//Check to make sure that user is authenticated

//before loading the JavaScript -- this prevents

//unauthorized viewing or misuse of data on a form

if (User.Identity.IsAuthenticated)

{

    //Resets the Drop Down List in Dialog Window

    GenerateResetDDLScript();

    //Adds a function to the drop down list to display a print, Excel, and

    //Word dialog Window based on a selected index

    GenerateDisplayPrintDialogScript();

    this.ddlActions.Attributes.Add("onchange", "Print(this)");

}

else

{

    Response.Redirect("NoAccess.aspx");

}