XXX

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Using Forms Authentication in ASP.NET - Part 1

Posted on 2005-11-21 08:56  XXXCccddd  阅读(387)  评论(0编辑  收藏  举报
Introduction

Classic ASP developers often had to "roll their own" authentication scheme, however, in ASP.NET much of the grunt work has been taken out. This article outlines how things have changed and how FormsAuthentication can be used to secure a Web site with a minimal amount of code.

In classic ASP, authentication was pretty much all or nothing. Either you were using integrated security (often referred to as the Microsoft Windows NT LAN Manager [NTLM] challenge/response authentication protocol ), Basic (referred to as clear text), or you had created your own type of authentication. This was often an arduous task. Forms Authentication allows developers to store the authentication information, such as username and password, in the Web.config file, or you can still use your own method, such as a database, eXtensible Markup Language (XML) file, or text file. The great thing about forms authentication is you no longer have to program the state-tracking portion. ASP.NET does it for you!

  • download source code
  • view demo

  • Forms Authentication Background

    Forms authentication uses cookies to allow applications to track users throughout their visit. The way ASP.NET handles forms authentication is probably very similar to the methods you have used in classic ASP. When a user logs in via forms authentication, a cookie is created and used to track the user throughout the site. If the user requests a page that is secure and has not logged in, then the user will be redirected to the login page. Once the user has been successfully authenticated, he/she will be redirected to their originally requested page.

    Standard Forms Authentication Setup

    Pages used: Default.aspx, Login.aspx, Web.config

    In the standard method of Forms Authentication, all user information is stored in the Web.config.

    Create a folder named standardForms under your webroot.

    Make this folder an application inside the Internet Services Manager. (This should be familiar territory if you ever used the Global.asa in ASP.)

    Web.config Overview

    The Web.config contains all of the configuration settings for an ASP.NET application. The idea is to put the control of the Web application in the hands of the developer rather than the system administrator. There are lots of options you can use here. This article details only the ones specific to Forms Authentication today.

    Web.config Code Using the Standard or "Credentials" Method

    Authentication

    Attributes

    Description

    Name

    This is the name of the cookie used for authentication. NOTE: If multiple applications want to use FormsAuthentication on the same machine, it is best to use unique names.

    Path

    Path used for cookie. The default value "/" often avoids errors with incorrect case in paths, since browsers are strictly case-sensitive when it comes to returning cookies.

    LoginUrl

    URL that unauthenticated users are redirected to.

    Protection

    Method used to protect cookie data. Default and suggested value is "All," which does validation and encryption.

    Timeout

    Number of minutes until authentication cookie expires.

    Credentials

    Attributes

    Description

    passwordFormat

    Format the password will be stored in. Valid values include Clear, SHA1, and MD5. SHA1 and MD5 are both hashing algorithms that make storing passwords in the Web.config more secure.

    User

    This is the area to store the username and password. You can secure the passwords by running the HashPasswordForStoringInConfigFile function to get the hashed password. I will demonstrate this later.

    Authorization

    Attributes

    Description

    Deny | Allow

    This section allows us to deny or allow users to the site. ? = anonymous/unauthenticated users and * means all users. This section also allows us to specify certain users, and allow or deny permissions.

    Web.config Code

    
    <configuration>
        <system.web>
            <customErrors mode="Off"/>
            <authentication mode="Forms">
                <forms name="appNameAuth" path="/" loginUrl="login.aspx" protection="All" timeout="30">
                    <credentials passwordFormat="Clear">
                        <user name="jeff" password="test" />
                        <user name="mike" password="test" />
                    </credentials>
                </forms>
            </authentication>
            <authorization>
                <deny users="?" />
            </authorization>
        </system.web>
    </configuration>
    
    

    Web.config Details

    Inside the Web.config above we have configured several options.

    Authentication
    The mode attribute for the <authentication> configuration section sets the authentication mode to Forms. Inside the <forms> section we are assigning the name attribute to "AppNameAuth". You might want to change the name of the cookie to something like "HRWebAuth", where HRWeb is the name of your application.

    Remember, if you are going to have multiple applications on the same machine, it's suggested that you use unique names for your cookies.

    Next, we set the path to the root of the application. We assign the loginUrl attribute a local page named loginUrl.aspx. You can use URL paths like https://secured.sumnurv.com for redirection as well. Setting protection to all is the suggested value. This means that the cookie will be both encrypted (using the Triple DES data-encryption standard) and validated.

    The validation algorithm comes from the machineKey element located in Machine.config. This data validation ensures that the cookie data wasn't tampered with during transit (someone sniffing traffic and responding with modified cookie).

    The timeout attribute refers to the number of minutes before a cookie expires and the user must log in again. In the credentials section, we add two users and their passwords. This is where FormsAuthentication will look to authenticate the users.

    Authorization
    In the authorization section, we want to ensure that no unauthenticated users can access the application. The "?" means anonymous users, so we set a deny flag for all anonymous users.

    Login.aspx Overview

    All user authentication logic is performed here. If you wish to verify a user's credentials against the Web.config, XML or text file, or database, this is the place it would happen. This example shows how to authenticate to the Web.config

    Login.aspx Code

    
    <%@Page Language="VB" %>
    <%@Import Namespace="System.Web.Security" %>
    <script language="VB" runat="server">
    Sub ProcessLogin(objSender As Object, objArgs As EventArgs)
    
      If FormsAuthentication.Authenticate(txtUser.Text, txtPassword.Text) Then
         FormsAuthentication.RedirectFromLoginPage(txtUser.Text, chkPersistLogin.Checked)
      Else
         ErrorMessage.InnerHtml = "<b>Something went wrong...</b> please re-enter your credentials..."
      End If
    
    End Sub
    </script>
    <html>
    <head>
    <title>Standard Forms Authentication Login Form</title>
    </head>
    
    <body bgcolor="#FFFFFF" text="#000000">
    <form runat="server">
    <table width="400" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td width="80">Username : </td>
        <td width="10"> </td>
        <td><asp:TextBox Id="txtUser" width="150" runat="server"/></td>
      </tr>
      <tr>
        <td>Password : </td>
        <td width="10"> </td>
        <td><asp:TextBox Id="txtPassword" width="150" TextMode="Password" runat="server"/></td>
      </tr>
      <tr>
      <tr>
        <td></td>
        <td width="10"> </td>
        <td><asp:CheckBox id="chkPersistLogin" runat="server" />Remember my credentials<br>
        </td>
      </tr>
      <tr>
        <td> </td>
        <td width="10"> </td>
        <td><asp:Button Id="cmdLogin" OnClick="ProcessLogin" Text="Login" runat="server" /></td>
      </tr>
    </table>
    <br>
    <br>
    <div id="ErrorMessage" runat="server" />
    </form>
    </body>
    </html>
    
    

    Login.aspx Details

    I have referenced the System.Web.Security namespace since we will be working with authentication. All methods of authentication reside in this namespace. FormsAuthentication is a class of the System.Web.Security namespace. Here we have a simple server-side form setup with one textbox and one password input for username and password. I have included a check box in case the user wants to have a permanent cookie set. The Submit button has an event "onclick" which runs a sub called ProcessLogin. Inside ProcessLogin we execute the Authenticate method of the FormsAuthentication class, passing in the given username and password. This method checks the credential's tags inside the Web.config for the username and password. If they match, then we execute the RedirectFromLoginPage with the username and persistent cookie state (if checked). This method then writes a cookie to the user's machine to track them and ensure they are authenticated. If the username and password do not match, then an error occurs and the user is notified.

    Default.aspx Overview

    This is the page the user is requesting or trying to access. Here we will display the currently authenticated user and the authentication type.

    Default.aspx Code

    
    <%@Page Language="VB" %>
    <%@Import Namespace="System.Web.Security" %>
    <script language="vb" runat="server">
    Sub SignOut(objSender As Object, objArgs As EventArgs)
      'delete the users auth cookie and sign out
      FormsAuthentication.SignOut()
      'redirect the user to their referring page
      Response.Redirect(Request.UrlReferrer.ToString())
    End Sub
    Sub Page_Load()
      'verify authentication
      If User.Identity.IsAuthenticated Then
        'display Credential information
        displayCredentials.InnerHtml = "Current User : <b>" & User.Identity.Name & "</b>" & _
           "<br><br>Authentication Used : <b>" & User.Identity.AuthenticationType & "</b>"
      Else
        'Display Error Message
        displayCredentials.InnerHtml = "Sorry, you have not been authenticated."
      End If
    End Sub
    </script>
    <html>
    <head>
    	<title>Forms Authentication</title>
    </head>
    <body bgcolor="#FFFFFF" text="#000000">
    <span class="Header">Forms Based Authentication using standard method</span>
    <br>
    <br>
    <div id="displayCredentials" runat="server" />
    <br>
    <br>
    <form runat="server">
      <asp:Button id="cmdSignOut" text="Sign Out" runat="server" onClick="SignOut" />
    </form>
    </body>
    </html>
    
    
    Again I have referenced the System.Web.Security namespace since we will need some of its methods and properties. This page contains a simple div element thatwill display the current credentials and authentication type used. There is also a signout input element that runs a sub that deletes the user's cookie. They are then redirected to the login page. In the Page_Load event, I check to see if the user has been authenticated using the User.Identity.IsAuthenticated property. This returns a Boolean value indicating whether or not the user has been authenticated. If the user is authenticated, we want to display the current user's name and the authentication method used. We can access the currently logged on user's name with the User.Identity.Name property. User.Identity.AuthenticationType returns the mode of authentication used. We also use a SignOut procedure that allows the user to sign out and deletes the cookie from the user's computer. This will even delete a persistent cookie.

    Conclusion

    I hope that this has given you the basic understanding of Forms Authentication and how it can be useful for you. If you have any questions or comments about the concepts or code in this article, please feel free to contact me.

    Resources

    Forms Authentication in ASP.NET -- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconhandlingformsauthenticationevents.asp

    Machine.config - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconstep1examiningconfigurationfiles.asp

    DES - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/security/secglos_9661.asp

    About the Author

    Jeff Gonzalez has been working in the IT industry for the last six years. He started his IT career as an NT4 administrator and network engineer. While working for a hosting company, he recognized the power of Windows DNA and sought out to learn everything he could about it. Since his foray into the Internet development world, he has worked on several e-commerce, e-business, and intranet applications. Jeff is currently working at Microsoft doing ASP.NET, VS.NET, and mobility controls support. He can be reached at rjg444@hotmail.com.