Authentication Example
Let's work on an example. First off I must modify the CONFIG.WEB from Listing 1 by removing the Windows authentication provider and replacing it with the cookie authentication provider. The new CONFIG.WEB is shown in Listing 2.
Listing 2. A modification of the CONFIG.WEB from Listing 1 that changes the authentication provider to cookie and also forces all users to authenticate.
First the mode is set to "cookie" and then the parameters are specified for cookie authentication. In the <cookie> node I set the decryption key to autogenerate. This is fine if you have a single Web server. If you are operating in a Web farm, however, you will probably want to set this value explicitly so that all nodes share it. The loginurl attribute is set to indicate which page unauthenticated users should be directed to—in this case login.aspx. Finally, the cookie attribute indicates what the name of the cookie should be. This is useful if you have several authentications schemes running on a single domain and don't want them to collide.
Cookie authentication can automatically validate against name/password pairs specified in a <credentials> section of the CONFIG.WEB file. This is convenient for testing but clearly presents problems in maintaining and scaling the authentication. A better choice would be to place the authentication information into a database like SQL Server. Listing 3 shows the TSQL required to create a table called Users, against which I will authenticate the user.
After creating this table and populating it with a few accounts, all that is left is to create the login form. The login form needs to collect the e-mail address and password of the user and then validate them by comparing them against the database. If they match, an authentication cookie will be sent to the user. Listing 4 contains a sample login form.
The login form first presents an ASP+-based login page to the user. Server-side controls are used to validate that the user has entered an e-mail address and password. Once these have been entered and the login button clicked, control is passed back to the server and the Login_Click() method is executed. Login_Click first checks to make sure the page is valid. If it is, a connection is built to the database and a query is run to retrieve the password of the user. This is compared against the input; if it matches, RedirectFromLoginPage is called to redirect the user back to the originally requested page and also write the authentication cookie to the browser.
There it is—custom authentication in 30 lines of code or less. Compared to the hoops you would have to jump through in ASP 3.0, this is amazing. I want to take authentication further, however. Authentication is great but in many cases what you actually want is authorization.