Welcome!

ColdFusion Authors: Yakov Fain, Maureen O'Gara, Nancy Y. Nee, Tad Anderson, Daniel Kaar

Related Topics: ColdFusion

ColdFusion: Article

Creating a Remember Me Login

Implementing a login script on your site

Many of my articles in this column have dealt with theoretical concepts and syntax of implementing those concepts in ColdFusion. In this article, I want to concentrate on the implementation steps you might take when building something.

Most Web applications have a "sign me up" feature that allows users to register. Registered users often have access to additional information or features that anonymous users don't. I'm going to walk you through the process of creating a simple login form, including database authentication and a "remember me" checkbox.

The Database
Before you start coding this application, you'll need to create a database. Most login schemes include a username and password. You can put that information in a table called Users. The table will also need a unique identifier, called a primary key in database terms. Here is a sample of data from the table:

UserIDUsernamePassword
1 Jeff Houser
2 CFDJ Author
3 ColdFusion Macromedia

Normally, a users table would have much more information than just a username and password. A name, address, and e-mail address are common additions. For the purposes of this example, we'll keep it simple. In a real-world application, you should consider encrypting the passwords in your database for security purposes. You can do this using ColdFusion's hash function. More information about the hash function is located at Click Here. You would use the hash function before saving the user's password into the database. For the purposes of this example, the passwords will remain in plain text.

You could implement a login script using just the users table we defined, but you'll find it limiting. The user is either logged in, or not logged in. There is no distinction between different levels of access. Suppose, for example, that anonymous users can look at products, registered users can post reviews of products, and admin users can change product information. You'll need something more than an "Authenticated" or "Not Authenticated" security structure. To do this we'll need to be able to group users into security groups. The SecurityGroups table will need a primary key and a group name. This is an example of some possible groups:

GroupIDGroupName
1 Admin
2 Anonymous
3 Registered

You'll also need an intersection or linking table to associate a user with his or her groups. This table will contain the GroupID and the UserID. The reason for creating this as a separate table is so that a single user can be in multiple groups, and a single group can have multiple users inside of it. This is known as a many-to-many relationship in the world of database design.

Here is an example of the SecurityUserGroups intersection table:

GroupIDUserID
1 (Admin) 1 (Jeff / Houser)
3 (Registered) 1 (Jeff / Houser)
3 (Registered) 3 (ColdFusion / Macromedia)

I added the group and user names next to the ID in parentheses to more easily show the relations. In a relational database, you would store only the ID. Our finished database structure is seen in Figure 1.

Before accessing this database from your ColdFusion code, you'll have to create a datasource in the ColdFusion administrator. Setting up the datasource is beyond the scope of this article, but it's a pretty straightforward task and you can read about setting up datasources for any database at Click Here.

The Login Form
With our database ready for use, we can start examining the login form. Most forms have two parts: an input page and a processing page. The input page asks for the username and password. It also has a checkbox for a "Remember Me" functionality. The code behind the form is shown in Listing 1.

The login form can be seen here: (Figure 2)

Enter Jeff in the username field and Houser in the password field. Check the Remember Me box and click submit. This brings us to the processing page (see Listing 2).

The RememberMe form variable value comes from a checkbox. If not checked when the form is submitted, the variable will not exist on the form processing page. You can use the cfparam tag to default if this situation occurs. The second step in the process is to validate the user's login information against the database. The cfquery tag is used to run the database query. The query joins the users table and the SecurityUserGroups table, where the username and password fields are equal to the input of the form. The query retrieves all information from the users table and the list of GroupIDs from the intersection table. If the database stored hashed passwords, we would change the query comparison to:

Users.password = '#hash(form.password)#'

This allows us to correctly compare two hashed values, not plain text passwords. This way we are keeping the user's password information secure.

We can check the RecordCount variable of our query to see if the query returned any rows. If the query did not return any rows, then the user did not enter a valid username and password combination. The login should fail. If rows are returned, then the login was a success. The code creates two session variables to process the login. To make use of session variables, you'll have to use the cfapplication tag. ColdFusion's application framework is beyond the scope of this article; however, you can read about it at Click Here.

The first value, LoggedIn, is a Boolean value that specifies that the user has logged in. I would default this value to false when the session is initialized. The second variable, groups, contains a list of all the groups that the user is in. The ValueList will give us a list from the column in the query.

Later in your application, when you have to decide whether a user should have access to a resource or not, you can use ListFind against the groups variable to see if the user is allowed. Here's an example:

 


<cfif ListFind(session.Groups, 1)>
 allow Access
<cfelse>
 No Access
</cfif>

If the user is in the admin group he or she can see the resulting HTML code, or access the corresponding resource. If not, then he or she will not be given access.

In this code, we are rolling our own security scheme. Many applications will use this approach, due to the complexity of security functions in the pre-CFMX days. However ColdFusion MX introduced a much improved security scheme using some new tags: cflogin, cfloginuser, and cflogout. They allow you to log in a user and set up a list of roles that ColdFusion will handle internally. The roles tie in with the role attributes of functions inside a ColdFusion component. These new tags are not in wide use yet, but they are definitely worth checking out if you are building an application from the ground up (livedocs.macromedia.com/coldfusion/6.1/htmldocs/appsecu6.htm). The reason I don't use them in my development is because my biggest project of the moment is being built to run off of BlueDragon, which does not yet support the functions.

Remembering the User
The one portion of code that I haven't explained yet is the "remember me" portion, so let's look at it in detail. There are many different ways you could implement the "remember me" portion of code. In most methods, you'll set a cookie on the user's machine, and store the same value in the database. When the user returns to the site, you can check to see if the cookie exists. If it does, you can retrieve the user's information from the database based on the cookie value. Simpler systems where security is not an issue may store the user's primary key ID. More complex systems with heavier security requirements may assign a UniqueID value, created with the CreateUUID function. Some systems I've worked with will store the CFID and CFTOKEN values generated by ColdFusion and used for session management, and use those to remember the user.

For the purposes of our sample, we are going to store the user's primary key as a cookie, but remember that in applications where security is a priority, this is probably not your best move. If form.RememberMe is set to true, then we use the cfcookie tag to create a cookie on the user's browser. We name the cookie UserID. The value is set to the UserID value returned from the query. It is set to never expire.

Setting the cookie is only the first step. When a user comes to the site, something will have to be implemented to check to see if we know who they are, or not. We are going to put this code in the Application.cfm. The code in the Application.cfm will look like an abbreviated version of the code in the login-processing page (see Listing 3).

First the code checks whether the IsLoggedIn session variable is defined. If it isn't, then this is the first time a user has come to the site. Next, we check if the UserID cookie variable exists. If it does, Next we run a query to get the user data based on the UserID. If the query finds the user, the code sets the two session variables. If not, it defaults them to the value. If the cookie doesn't exist at all, it defaults the session values.

Conclusion
This article demonstrated a simple method for implementing a login script on your site. It incorporated many common security elements and used many common ColdFusion tags. The approach I took in this article is not the only approach that could be used, but it is simple yet elegant. For those who want more, you can check out the authenticationAPI included in Macromedia's DRK 7. In my next column I'll talk more in depth about ColdFusion's application framework and the cfapplication tag, including setting up the session and application scopes.

More Stories By Jeffry Houser

Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...