Using ASP.NET Forms Authentication

for RuBoard

In Chapter 13, Forms Authentication was introduced as a new feature of ASP.NET. Now that we have covered everything behind that sample, let's look at it again and "tweak" a few things this time. Starting with the web.config file for the FormAuth site, Listing 14.9 shows the complete web.config file.

Listing 14.9 web.config File for FormAuth Application
 <?xml version="1.0" encoding="utf-8" ?> <configuration>  <system.web> <authentication mode="Forms"> <forms name=".NETBOOKDEMO" loginUrl="login.aspx" protection="All" timeout="30" path="/" /> </authentication> <authorization>         <deny users="?" /> </authorization> <globalization requestEncoding="utf-8" responseEncoding="utf-8" />  </system.web> </configuration> 

Now that our Web will be configured correctly, we have to make at least one page. As mentioned in Chapter 13, the element of authentication mode in the web.config file can take four possible values. Because we chose "Forms" , we must have a page for login and failed logins. This can be the same page. Listing 14.10 shows the default page of this site, login.aspx .

Listing 14.10 login.aspx (Complete)
 <%@ Import Namespace="System.Web.Security " %> <html>  <script language="C#" runat="server">     void Login_Click(Object sender, EventArgs E) {       // authenticate user: this samples accepts only one user with       // a name of user@domain.com and a password of 'password' //in a real world scenario, this would be code that hit a database of some //sort to validate a user after validating the input to prevent against script.       // injection and SQL injection attacks       if ((UserEmail.Value == "user@domain.com") && (UserPass.Value == "password")) {         FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked);       }       else {         Msg.Text = "Invalid Credentials: Please try again";  // unless you validate or encode *all* untrusted data before echoing it back,  // you have a CSS attack         Msg.Text += " You entered " + Server.HtmlEncode(UserEmail.Value) + "<BR>";         Msg.Text += " and a password of " + Server.HtmlEncode(UserPass.Value);       }     }  </script>  <body>   <form runat="server" ID="Form1">    <h3><font face="Verdana">Login Page</font></h3>    <table>     <tr>      <td>Email:</td>      <td><input id="UserEmail" type="text" runat="server" NAME="UserEmail" /></td>      <td><ASP:RequiredFieldValidator ControlToValidate= "UserEmail" Display="Static" graphics/ccc.gif ErrorMessage="*" runat="server" ID="Requiredfieldvalidator1" /></td>     </tr>     <tr>      <td>Password:</td>      <td><input id="UserPass" type="password" runat="server" NAME="UserPass" /></td>      <td><ASP:RequiredFieldValidator ControlToValidate="UserPass" Display="Static" graphics/ccc.gif ErrorMessage="*" runat="server" ID="Requiredfieldvalidator2" /></td>     </tr>     <tr>      <td>Persistent Cookie:</td>      <td><ASP:CheckBox id="PersistCookie" runat="server" />      </td>      <td></td>     </tr>    </table>    <asp:button text="Login" OnClick="Login_Click" runat="server" ID="Button1" />     <asp:Label id="Msg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" graphics/ccc.gif />   </form>  </body> </html> 

What happens here is that if the login fails, the user is automatically redirected to the loginURL value set in the web.config file. Ideally, users would be stored in a database, but sometimes this is just not possible. For such an event, usernames and passwords can be stored in a web.config file. Obviously, you wouldn't store the passwords as plain text, so you encrypt them. Depending on the encryption scheme used, you would get different results for a hash. All of this information is stored by adding a credentials element to the web.config file and storing your user information in that file. An important attribute of this element is the decryptionKey value. If you plan to use these pages on more than one server, the decryptionKey value must be the same on all machines. The default value is autogenerate , but it can be any string value you desire consisting of hexadecimal characters . The next attribute that must be the same across all machines is the passwordFormat attribute; this can be Clear (not a good idea), MD5, or SHA-1. The information stored is a hash of the decryptionKey value and the password value using the passwordFormat algorithm. Because you're not going to know what the value of a specific hashed password is, you need a function that can take care of this for you. Listing 14.11 demonstrates the functionality necessary to create SHA-1 hashes of a password. To try this code on its own, simply paste it into the Page_Load event for an ASPX file, save the page to a working virtual directory, and navigate to http://localhost/<whateverfilenameyougaveit.aspx?password . You should see a result similar to 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8 . Alternatively, if you set the encryption scheme to MD5, you would get a value of 5F4DCC3B5AA765D61D8327DEB882CF99 . These values will differ depending on any padding that you may use to increase security.

Listing 14.11 Sample Encryption Function
 string s_QString = this.Page.Request.QueryString.ToString(); if (s_QString.Length > 0) {      string hashedPass;      string passToHash;      passToHash = this.Page.Request.QueryString._ ToString();      hashedPass =_ FormsAuthentication.HashPasswordForStoringInConfigFile(passTo Hash, "md5");      Response.Write(hashedPass);} 

This function simply displays the encrypted password, but it demonstrates how simple it is using the .NET platform to implement security features.

Another task that forms authentication handles is the creation of a cookie. After a session is started and a user is authenticated, the cookie stores encrypted information regarding that user until the browser is closed. In Chapter 13, Tables 13.1 and 13.2 illustrate the possible configuration settings for where the cookie is stored, how long it will live, encryption settings, and its name. So now we can put all of this together in a sample that will authenticate users based on entries in the web.config file and uses the SHA-1 algorithm for encryption.

First, we'll make an entry in the web.config file for our test user, user@domain.com . I'll use the code in Listing 14.11 to create the hashed value for the word password and add the credentials. This entry is shown in Listing 14.12. Because we will be using this method of authentication, we have to add the credentials element to our authentication element.

Listing 14.12 User Entry in web.config File
 <authentication mode="Forms">      <forms name=".NETBOOKDEMO" loginUrl="login.aspx" protection="All" timeout="30" graphics/ccc.gif path="/">      <credentials passwordFormat="SHA1" >       <user name="user@domain.com" password="5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8"/>      </credentials>    </forms> </authentication> 

Of course, in a real world application, we would have a relational database for such accounts. Making changes to the web.config file prompts an application to restart, this could be very inconvenient in a high-visibility application. The next step is to change the login functionality in our login page, login.aspx . Listing 14.13 shows the Login_Click function.

Listing 14.13 New Login_Click Function
 void Login_Click(Object sender, EventArgs E) {      if(FormsAuthentication.Authenticate(UserEmail.Value, UserPass.Value))      {      FormsAuthenticationTicket fTick = new FormsAuthenticationTicket_ (UserEmail.Value, graphics/ccc.gif false, 5000);      FormsAuthentication.RedirectFromLoginPage(UserEmail.Value, PersistCookie.Checked);         }      else      {       Msg.Text = "Invalid Credentials: Please try again";    Msg.Text += " <BR>You entered " + Server.HtmlEncode(UserEmail.Value) + "<BR>";       Msg.Text += " and a password of " + Server.HtmlEncode(UserPass.Value); }     } 

Notice the introduction of the FormsAuthenticationTicket object. This is what handles communications based on the setting for the authentication mode element from which it gets its information.

NOTE

The .NET Platform also integrates with Microsoft Passport technologies. Working with Passport is very similar to working with FormsAuthentication . When a request is made to a protected resource that has a FormsAuthentication method of Passport, the request, if no valid Passport form is detected , is redirected to a Passport login server where, on authentication, the Ticket is passed back to the original server where it handles the rest of the transaction.


for RuBoard


. NET Framework Security
.NET Framework Security
ISBN: 067232184X
EAN: 2147483647
Year: 2000
Pages: 235

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net