Click here to close now.

Welcome!

You will be redirected in 30 seconds or close now.

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

Related Topics: ColdFusion

ColdFusion: Article

Implementing HTTP Basic Authentication

Route around many of the common limitations of traditional forms-based authentication

How to Implement Basic Authentication with ColdFusion
The first time a Web browser requests a page that's protected by Basic authentication, the Web server needs a way to tell it that it should stop and ask the user for login information. It does this by sending a response to the initial request with the status code 401 ("Access Denied"). In this response, it also sends information about what types of authentication it's willing to accept (this is the "WWW-Authenticate" header). In this article, we're only discussing Basic Authentication, but other more complex (and more secure) methods exist such as Digest authentication and Microsoft's proprietary NTLM authentication. Along with the 401 response the server also sends a user-friendly (or at least user-readable) explanation of why access is being denied.

When the browser gets the 401 response, before showing the user the "Access Denied" message, it prompts for a user name and password. If the user provides credentials, the browser repeats the request and includes the user name and password in an "Authorization" request header. If the credentials are sufficient, the server then sends the requested page with a 200 ("OK") status code. If the credentials aren't acceptable to the server, it simply sends back the same 401 response, which makes the browser prompt the user again. If the user declines to provide credentials (by clicking a "Cancel" button on the password prompt, for example), or fails to provide acceptable credentials a certain number of times (usually three, although it's up to the Web browser to decide), the browser stops prompting the user and shows the user the "Access Denied" message provided by the server.

Listing 1 shows the code needed to implement Basic Authentication. This code should be included at the top of any page that needs to be protected by authentication (an Application.cfm file is a good place, for example).

The first lines use the built-in ColdFusion function GetHttpRequestData() to retrieve complete information on the request headers sent by the client and ensure that our session-level user variable is initialized. Then the code checks to see if the client has provided the "Authorization" header that contains the login and password. The "Authorization" header consists of two parts separated by a single space: first, the authentication scheme (in this case "Basic"); and second, the user name and password separated by a colon and Base64-encoded to protect them from character set issues during transmission. The user name and password are decoded using the ToBinary() and ToString() functions, and the application verifies that they're correct (obviously this part will vary from application to application). If the user hasn't been logged in either by providing incorrect credentials or by not providing any at all, the response code is set to 401 and the "WWW-Authenticate" response header is added. Finally, a user-friendly "Access Denied" message is added to the response and execution is stopped so the server sends only the "Access Denied" message back to the client.

Even if the user has cookies disabled, so the user's session doesn't persist from request to request, the user won't be prompted again for a login and password. However, in this case, you won't be able to store any other data in the session scope without resorting to passing session identifiers as URL parameters.

Since the browser is getting accurate response codes throughout the transaction, there's no need to write code to redirect the user after a successful login. This is an additional benefit of using Basic authentication and means that your application fully supports deep linking and bookmarking without any extra code.

The Authentication Realm
There's one additional piece of information that the server sends in the "WWW-Authenticate" header: the authentication realm. The realm is defined as a string that uniquely identifies the set of resources on the server that all use the same user account source. The browser assumes that if it has prompted the user for a login and password for a resource on a given server, it can reuse the same credentials for another resource in the same realm on the same server.

Although the specification for Basic authentication discourages the use of the realm for any purpose other than matching it for equality against other realm values, in practice the realm actually has another important function. When most browsers prompt the user for login credentials, they show the realm as a description of the application the user is logging in to. So it's a good idea to set the realm in your authentication code to a brief description of your application (this description would replace the string "MyApplication" in Listing 1).

Caching of Credentials: The End of Session Expiration
When a browser gets a 401 ("Access Denied") message in response to a request for a given resource, it checks to see if the realm specified in the "WWW-Authenticate" header matches any realms it has already authenticated against on the current server for the current browser session. If it finds credentials that have been accepted for that realm, it retries the request using those credentials (prompting the user for credentials only if the cached credentials are rejected by the server). The browser also assumes that resources in subdirectories below the resources for which it has already been prompted to authenticate will be part of the same realm and preemptively sends the cached credentials the first time it requests these resources. These two facts contribute to one of the biggest advantages of Basic authentication: the end of session expiration messages.

Examine Listing 1 again and consider what happens if the user has been previously authenticated but has been inactive enough that the session expired. On the next request, a new session is initiated by the ColdFusion server and SESSION.loggedInUserName is set to an empty string. If the browser has previously requested the page, it will have preemptively sent the login credentials; if not, it will check its cache and see that it already has credentials for the specified realm and it will repeat the request, providing the cached credentials. In either case, the user has been automatically logged back into the application without being prompted! This provides a much smoother and less confusing experience for the user.

Keep in mind that this may have some affect on your application architecture. If you're using the session scope only to cache information that's already stored in a database somewhere, your application can probably be converted to Basic authentication with no issues. However, if you store temporary data in the session scope (such as shopping cart information), you may have to consider a different approach since the user may have multiple ColdFusion sessions over the course of what they consider a single session of interacting with the Web application. Just remember that a user session might be initialized on any page of your application.

Limitations of Basic Authentication
Basic authentication isn't without its limitations. First and foremost, it's important to realize that the user name and password is transmitted from the browser to the Web server in unencrypted clear text. (The Base64 encoding isn't a security measure - it's designed to be easily reversible.) If you consider the data in your application to be sensitive, you should definitely use an additional security layer such as SSL to protect the transmission of the user name and password (as well as the data). That being said, this lack of encryption is a limitation that's common to both forms-based and Basic authentication.

The other significant limitation of Basic authentication, and the only major drawback to using it over forms-based authentication, is that it provides much less opportunity for context around the login and password. A forms-based solution can show information around the login box explaining the format of the login and, in the case of password errors, can provide detailed information about what went wrong. Additionally, the login prompt can be customized to match the look-and-feel of the rest of the application. When implementing HTTP Basic authentication, you should provide an entry page that isn't authenticated that provides this information so the user is prepared to enter the appropriate login and password information.

Conclusion
Basic authentication provides an alternative to traditional forms-based authentication methods. By sticking closely to the HTTP specification, this method leverages features built in to the Web browser to prevent confusing session expiration problems and the need to code around other limitations in non-standard forms-based authentication methods.

More Stories By Patrick Correia

Patrick Correia is a Web developer for Clough Harbour & Associates LLP, an east coast multi-disciplined engineering firm. A Certified Advanced ColdFusion MX Developer based in Albany, New York, he has spent the last five years developing ColdFusion-based business process improvement solutions for the firm's numerous municipal and private clients.

Comments (1) View Comments

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.


Most Recent Comments
MikeR 06/08/06 11:43:56 PM EDT

Interesting article but it failed to mention the huge flaw with basic auth.

Basic authentication can't be used for most real-world sites because:
(1) There is now way for the user to log out short of closing all browser windows.
and (2) There is no practical way for the site to logout or timeout a user.

@ThingsExpo Stories
We’re entering a new era of computing technology that many are calling the Internet of Things (IoT). Machine to machine, machine to infrastructure, machine to environment, the Internet of Everything, the Internet of Intelligent Things, intelligent systems – call it what you want, but it’s happening, and its potential is huge. IoT is comprised of smart machines interacting and communicating with other machines, objects, environments and infrastructures. As a result, huge volumes of data are being generated, and that data is being processed into useful actions that can “command and control” thi...
Building low-cost wearable devices can enhance the quality of our lives. In his session at Internet of @ThingsExpo, Sai Yamanoor, Embedded Software Engineer at Altschool, provided an example of putting together a small keychain within a $50 budget that educates the user about the air quality in their surroundings. He also provided examples such as building a wearable device that provides transit or recreational information. He then reviewed the resources available to build wearable devices at home including open source hardware, the raw materials required and the options available to power s...
In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect at GE, and Ibrahim Gokcen, who leads GE's advanced IoT analytics, focused on the Internet of Things / Industrial Internet and how to make it operational for business end-users. Learn about the challenges posed by machine and sensor data and how to marry it with enterprise data. They also discussed the tips and tricks to provide the Industrial Internet as an end-user consumable service using Big Data Analytics and Industrial Cloud.
SYS-CON Events announced today that BMC will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. BMC delivers software solutions that help IT transform digital enterprises for the ultimate competitive business advantage. BMC has worked with thousands of leading companies to create and deliver powerful IT management services. From mainframe to cloud to mobile, BMC pairs high-speed digital innovation with robust IT industrialization – allowing customers to provide amazing user experiences with optimized IT per...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
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 styles ...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
Collecting data in the field and configuring multitudes of unique devices is a time-consuming, labor-intensive process that can stretch IT resources. Horan & Bird [H&B], Australia’s fifth-largest Solar Panel Installer, wanted to automate sensor data collection and monitoring from its solar panels and integrate the data with its business and marketing systems. After data was collected and structured, two major areas needed to be addressed: improving developer workflows and extending access to a business application to multiple users (multi-tenancy). Docker, a container technology, was used to ...
The true value of the Internet of Things (IoT) lies not just in the data, but through the services that protect the data, perform the analysis and present findings in a usable way. With many IoT elements rooted in traditional IT components, Big Data and IoT isn’t just a play for enterprise. In fact, the IoT presents SMBs with the prospect of launching entirely new activities and exploring innovative areas. CompTIA research identifies several areas where IoT is expected to have the greatest impact.
2015 predictions circa 1970: houses anticipate our needs and adapt, city infrastructure is citizen and situation aware, office buildings identify and preprocess you. Today smart buildings have no such collective conscience, no shared set of fundamental services to identify, predict and synchronize around us. LiveSpace and M2Mi are changing that. LiveSpace Smart Environment devices deliver over the M2Mi IoT Platform real time presence, awareness and intent analytics as a service to local connected devices. In her session at @ThingsExpo, Sarah Cooper, VP Business of Development at M2Mi, will d...
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In this session, James Kirkland, Red Hat's Chief Architect for the Internet of Things and Intelligent Systems, will describe how to revolutionize your architecture and...
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo, June 9-11, 2015, at the Javits Center in New York City. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
We are reaching the end of the beginning with WebRTC, and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) i...
SYS-CON Events announced today that MetraTech, now part of Ericsson, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Ericsson is the driving force behind the Networked Society- a world leader in communications infrastructure, software and services. Some 40% of the world’s mobile traffic runs through networks Ericsson has supplied, serving more than 2.5 billion subscribers.
Thanks to widespread Internet adoption and more than 10 billion connected devices around the world, companies became more excited than ever about the Internet of Things in 2014. Add in the hype around Google Glass and the Nest Thermostat, and nearly every business, including those from traditionally low-tech industries, wanted in. But despite the buzz, some very real business questions emerged – mainly, not if a device can be connected, or even when, but why? Why does connecting to the cloud create greater value for the user? Why do connected features improve the overall experience? And why do...
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York City, NY. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An active participa...
Imagine a world where targeting, attribution, and analytics are just as intrinsic to the physical world as they currently are to display advertising. Advances in technologies and changes in consumer behavior have opened the door to a whole new category of personalized marketing experience based on direct interactions with products. The products themselves now have a voice. What will they say? Who will control it? And what does it take for brands to win in this new world? In his session at @ThingsExpo, Zack Bennett, Vice President of Customer Success at EVRYTHNG, will answer these questions a...