ColdFusion In Context: Login and Site Protection

How can you use cookies to show subsequent pages in your application that you've authenticated a user? Nearly every site needs a way to do this, but few talk about how it's done. It's complicated by a quirk of HTTP that keeps cookies from being set by a page that you exit using CFLOCATION.

Here's a tool you can use to easily set a cookie at login and then protect the rest of your site from individuals who don't have this cookie. Along the way, you'll determine the previous page; delete a cookie; read a cookie; change pages; determine where you are; set a cookie; reload the current page; and use authenticate.cfm with the CONTAINS operator to protect the rest of your application.

You'll build three pages plus a throwaway "site" represented by a directory and a destination page that takes the place of the rest of your site.

Make your Throwaway Site

This is easy. Create an empty directory and put a .cfm page in it to be your goal after login. Consider it to be the foyer of the motel after the doorman has buzzed you in when you're traveling on business late at night. I've called it "foyer.cfm" in this example.

Make the Login Page

This can be the home page for your application where the user "knocks" for entry. You would probably call it index.cfm; I've called it "knock.cfm" here to keep it from getting lost on your drive.
Determine the "Previous" Page
First, you want an easy way to let users whose login failed that their input was received but that they were not allowed to leave this page. (The gate you'll build later, gate.cfm, could send you a URL variable to tell you this, but just the fact that the user was turned away tells you that the login failed.)

Interestingly, because the CFLOCATION tag was used to bring you back here, it's as if you never left, as if the page on which it was used never finished loading. That's why you test for the current page (knock.cfm), not the page the user was kicked out of, as the referring page.

<cfif findnocase("knock.cfm",cgi.http_referer)>
  <p>Your login failed.
</cfif>
Delete a Cookie and Create the Login Form
If login is successful, gate.cfm will set a cookie called "key" with a certain value. Therefore, you want to get rid of this cookie before a new login attempt. This form uses a single employee ID instead of a Username and Password - this is common for many business applications - but the principle is the same regardless of how many fields you use.

<cfcookie name="key" value="" expires="now">
<form action="Gate.cfm" name="knock" method="post">
Enter employee ID: 
<input type="text" name="employeeID" value="" size="10" maxlength="8">
<input type="submit" name="submit" value="OK?">
</form>

Create the Gatekeeper

This is your authentication page, called "gate.cfm" in this example. You can make the authentication method as complex as you like, but the net result in this case is to set a cookie if you trust the user and bounce the user out the door if you don't.
Read a Cookie; Change Pages
Test to see if the cookie exists before trying to read it. The cookie's contents can be as simple or as complex as you want. Instead of "adsf", the cookie in a real application should contain encoded information or be part of a complex relationship to make it more useful and harder to forge.

Notice that we're reading a previously set cookie, not writing one; so, it's OK to use CFLOCATION here. The "foyer" represents your site's main menu after login.

The login and authentication pages will have less automatic protection than the other pages in your site; so, you need to be especially careful to avoid errors that might strand a user here. Therefore, check for the presence of your form variables before trying to use them and bounce a user that doesn't present them.

<cfif isDefined("cookie.key")>
  <cfif cookie.key eq "asdf">
    <cflocation URL="foyer.cfm">
  </cfif>
</cfif>
<cfif not isDefined("form.employeeID")>
  <cflocation URL="knock.cfm">
</cfif>
Determine Where You Are; Set a Cookie; Reload the Current Page; and Move Forward
The cf_template_path gives the location of the current page; you could hard-code this instead, but I've used it here to show how easy it is to get this information. Setting the cookie is as easy as deleting it was. Omitting the "expires" attribute causes the cookie to vanish when the user closes the browser, but it's available in the meantime to be read by the site.

Using the meta tag to refresh the location is ALMOST compatible with setting cookies. If you refresh to a page and let authenticate.cfm test for the cookie on that page, the test fails. Therefore, you need to refresh to a page that authenticate.cfm is not protecting with the cookie test. You could create an intermediate page whose only function is to be ignored by application.cfm and move you along to the foyer, or you can do what we've done here and refresh to the current page. The code below reloads the page. The code above sees the newly written cookie and moves to the foyer when the page reloads.

<cfset self="cgi.cf_template_path">
<cfif form.employeeID eq "frank">
  <cfcookie name="key" value="asdf">
  <cfoutput><meta http-equiv="Refresh" content="0 URL=#self#"></cfoutput>
<cfelse>
  <cflocation URL="knock.cfm">
</cfif>

Protect the Application

Apart from recording who's doing what, the whole point of requiring a login is to restrict uncleared users from interacting with your application. In general, you don't want anyone who doesn't pass the cookie test (whatever it is) to reach your application's pages.

The only exceptions are the pages you can't secure this way (like the login and gate) or don't want to secure (like introductory help or new account requests). Exclude those pages from your test by listing them and then seeing if the filename the user's trying to reach is on the list.

Because "and" stops as soon as it encounters a failure, we can combine the test to see if the cookie exists with the test of the cookie's contents as shown. Save this code as Application.cfm to boot failures out of the application.

<cfif "KNOCK.CFM;GATE.CFM" does not contain uCase(getFileFromPath(cgi.cf_template_path))>
  <cfif not (isDefined("cookie.key") and (cookie.key eq "asdf"))>
    <cflocation url="knock.cfm">
  </cfif>
</cfif>
Try to go to foyer.cfm. If you are not logged in, Application.cfm will dump you to knock.cfm. If you enter "frank" as the employee ID, gate.cfm will write the cookie to your browser that you need to go to protected pages. This may not look like much, but you've just used three tiny files to admit wanted users and exclude unwanted ones. It's a reasonable foundation for the rest of your security measures. =Marty=

[The tag used for refresh needs to be wrapped in cfoutput tags as shown so the variable "self" will be properly expanded.]