Adding Form Security to the Sample Application


At this point your sample application has two pages: One is a login form and the other is basically a form with two buttons (one that says High security task and one that says Low security task). Let's make the login form fully functional.

To add form security to the sample application:

  1. Open the file Web.config.

  2. If you look through the file you'll find a section called authentication. It currently says <authentication mode="Windows" />. Replace the entry with the code in Figure 11.30 .

    Figure 11.30 The trick to having the program always transfer control to the login page first is the line that's highlighted. The question mark stands for unauthenticated users. In other words, deny access to all pages for unauthenticated users.
     <authentication mode="Forms" >    <forms loginUrl="login.aspx"    protection="All" /> </authentication> <authorization>  <deny users="?" />  </authorization> 
  3. Open the login.aspx page and doubleclick on the login button so that the wizard adds a skeleton for the Click event.

  4. Inside the Click event, add the code in Figure 11.31 . As you can see the code doesn't really look up names in a database (although it wouldn't be very difficult to do this). It just recognizes three emails: robertjordan@fantasy.com , douglasadams@ funny .com , and josemojica@tech.com . (In case you're wondering who this Jose Mojica guy is, he's just the guy who wrote the book you're reading. Thank you for buying it, by the way).

    Figure 11.31 I don't recommend storing all the names of your users and their passwords in plain text in your code, but it makes it easier to write the sample code.
     private void btnLogin_Click( object sender, System.EventArgs e) {    string username = "";    switch (txtEmail.Text)    {       case "robertjordan@fantasy.com":       if (txtPassword.Text == "password")       {          username="Robert Jordan";       }       break;       case "douglasadams@funny.com":       if (txtPassword.Text == "password")       {          username="Douglas Adams";       }       break;       case "josemojica@tech.com":       if (txtPassword.Text == "password")       {          username="Jose Mojica";       }       break;    }    if (username != "")    {       FormsAuthentication.       RedirectFromLoginPage(       username,false);    }    else    {       lblError.Text = "Incorrect userid or password";    } } 
  5. Right-click on the file global.aspx and select View code from the code menu.

  6. Find the function called Application_AuthenticateRequest and replace it with the code in Figure 11.32 . This function executes on each request after the FormsAuthenticationModule has had a chance to verify that the user is authenticated. If the user has been authenticated, you can get the user 's name with Context.User.Name . The code then creates a GenericPrincipal object that has the user's name plus the groups that the user belongs to.

    Figure 11.32 When the user attempts to reach another page without being authenticated, the authentication module routes the call to the login page but records in the query string the name of the page that the user had requested . This method marks the user as authenticated and tells the module to forward the request to the page the user had intended to go.
     private void btnLogin_Click( object sender, System.EventArgs e) {    string username = "";    switch (txtEmail.Text)    {       case "robertjordan@fantasy.com":       if (txtPassword.Text == "password")       {          username="Robert Jordan";       }       break;       case "douglasadams@funny.com":       if (txtPassword.Text == "password")       {          username="Douglas Adams";       }       break;       case "josemojica@tech.com":       if (txtPassword.Text == "password")       {          username="Jose Mojica";       }       break;    }    if (username != "")    {  FormsAuthentication.   RedirectFromLoginPage(   username,false);  }    else    {       lblError.Text =       "Incorrect userid or password";    } } 
  7. Open the secured.aspx form and doubleclick on the first task button. The wizard will add code to handle the Click event. Enter the code in Figure 11.33 inside the Click event. This code is actually quite amazing, because it shows how little code we have to write to implement group -based (or role-based) security in our code. This code creates a PrincipalPermission object. The first parameter in the constructor is the user name (null means any user). The second parameter is the role we require. Then, when we call the Demand method in the object, the code will trigger an error if the current user is not part of the role.

    Figure 11.33 Checking if the user has rights to access the code is a matter of creating a PrincipalPermission object and calling Demand on it. After those two lines of code you can write all the rest of the code for the function. If the user doesn't have permission, the function will exit with an exception; otherwise it will continue normally.
     private void btnLowTask_Click(object sender, System.EventArgs e) {    PrincipalPermission perm = new    PrincipalPermission(null,"User");    perm.Demand(); } 
  8. Go back to the secured.aspx form view and double-click on the second button. The wizard will add code to handle the Click event. Add the code in Figure 11.34 . This code is similar to the code in Figure 11.33 except that it demands that the user be part of the Admin group.

    Figure 11.34 The High task button click function ensures that the user is a member of the Admin group. In the code, Jose Mojica is the only user to have Admin rights.
     private void btnHighTask_Click( object sender, System.EventArgs e) {    PrincipalPermission perm = new    PrincipalPermission(null,"Admin");    perm.Demand(); 
  9. Execute the program by pressing F5. Try entering different names in the login screen and clicking the login button. Once the program transfers control to the secured form, try clicking each of the buttons.

graphics/tick.gif Tips

  • If you attempt to go to any page without logging in, ASP.NET will transfer control to the login window. Then after you've logged in, it will transfer control to the page you request.

  • Right now, if you enter a user that doesn't have Admin rights and click the High security task button, you'll get an unhandled exception. In the next section we'll take care of displaying something nice when there's an error.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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