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
The 3rd International WebRTC Summit, to be held Nov. 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA, announces that its Call for Papers is now open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 15th International Cloud Expo, 6th International Big Data Expo, 3rd International DevOps Summit and 2nd Internet of @ThingsExpo. WebRTC (Web-based Real-Time Communication) is an open source project supported by Google, Mozilla and Opera that aims to enable bro...
As more and more data is generated from a variety of connected devices, the need to get insights from this data and predict future behavior and trends is increasingly essential for businesses. Real-time stream processing is needed in a variety of different industries such as Manufacturing, Oil and Gas, Automobile, Finance, Online Retail, Smart Grids, and Healthcare. Azure Stream Analytics is a fully managed distributed stream computation service that provides low latency, scalable processing of streaming data in the cloud with an enterprise grade SLA. It features built-in integration with Azur...
With the proliferation of connected devices underpinning new Internet of Things systems, Brandon Schulz, Director of Luxoft IoT – Retail, will be looking at the transformation of the retail customer experience in brick and mortar stores in his session at @ThingsExpo. Questions he will address include: Will beacons drop to the wayside like QR codes, or be a proximity-based profit driver? How will the customer experience change in stores of all types when everything can be instrumented and analyzed? As an area of investment, how might a retail company move towards an innovation methodolo...
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, November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be.
SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.
SYS-CON Events announced today the Containers & Microservices Bootcamp, being held November 3-4, 2015, in conjunction with 17th Cloud Expo, @ThingsExpo, and @DevOpsSummit at the Santa Clara Convention Center in Santa Clara, CA. This is your chance to get started with the latest technology in the industry. Combined with real-world scenarios and use cases, the Containers and Microservices Bootcamp, led by Janakiram MSV, a Microsoft Regional Director, will include presentations as well as hands-on demos and comprehensive walkthroughs.
Containers are not new, but renewed commitments to performance, flexibility, and agility have propelled them to the top of the agenda today. By working without the need for virtualization and its overhead, containers are seen as the perfect way to deploy apps and services across multiple clouds. Containers can handle anything from file types to operating systems and services, including microservices. What are microservices? Unlike what the name implies, microservices are not necessarily small, but are focused on specific tasks. The ability for developers to deploy multiple containers – thous...
Contrary to mainstream media attention, the multiple possibilities of how consumer IoT will transform our everyday lives aren’t the only angle of this headline-gaining trend. There’s a huge opportunity for “industrial IoT” and “Smart Cities” to impact the world in the same capacity – especially during critical situations. For example, a community water dam that needs to release water can leverage embedded critical communications logic to alert the appropriate individuals, on the right device, as soon as they are needed to take action.
WebRTC services have already permeated corporate communications in the form of videoconferencing solutions. However, WebRTC has the potential of going beyond and catalyzing a new class of services providing more than calls with capabilities such as mass-scale real-time media broadcasting, enriched and augmented video, person-to-machine and machine-to-machine communications. In his session at @ThingsExpo, Luis Lopez, CEO of Kurento, will introduce the technologies required for implementing these ideas and some early experiments performed in the Kurento open source software community in areas ...
SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies leverage disruptive technologies to optimize revenue-generating systems, has been named “Bronze Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Founded in 1997, Pythian is a global IT services company that helps companies compete by adopting disruptive technologies such as cloud, Big Data, advanced analytics, and DevOps to advance innovation and increase agility. Specializing in designing, imple...
Consumer IoT applications provide data about the user that just doesn’t exist in traditional PC or mobile web applications. This rich data, or “context,” enables the highly personalized consumer experiences that characterize many consumer IoT apps. This same data is also providing brands with unprecedented insight into how their connected products are being used, while, at the same time, powering highly targeted engagement and marketing opportunities. In his session at @ThingsExpo, Nathan Treloar, President and COO of Bebaio, will explore examples of brands transforming their businesses by t...
In his session at @ThingsExpo, Lee Williams, a producer of the first smartphones and tablets, will talk about how he is now applying his experience in mobile technology to the design and development of the next generation of Environmental and Sustainability Services at ETwater. He will explain how M2M controllers work through wirelessly connected remote controls; and specifically delve into a retrofit option that reverse-engineers control codes of existing conventional controller systems so they don't have to be replaced and are instantly converted to become smart, connected devices.
With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts, GM of Platform at FinancialForce.com, will discuss the value of business applications on wearable ...
SYS-CON Events announced today that Micron Technology, Inc., a global leader in advanced semiconductor systems, will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Micron’s broad portfolio of high-performance memory technologies – including DRAM, NAND and NOR Flash – is the basis for solid state drives, modules, multichip packages and other system solutions. Backed by more than 35 years of technology leadership, Micron's memory solutions enable the world's most innovative computing, consumer,...
17th Cloud Expo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterprises are using some form of XaaS – software, platform, and infrastructure as a service.
SYS-CON Events announced today that the "Second Containers & Microservices Expo" will take place November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities.
As more intelligent IoT applications shift into gear, they’re merging into the ever-increasing traffic flow of the Internet. It won’t be long before we experience bottlenecks, as IoT traffic peaks during rush hours. Organizations that are unprepared will find themselves by the side of the road unable to cross back into the fast lane. As billions of new devices begin to communicate and exchange data – will your infrastructure be scalable enough to handle this new interconnected world?
While many app developers are comfortable building apps for the smartphone, there is a whole new world out there. In his session at @ThingsExpo, Narayan Sainaney, Co-founder and CTO of Mojio, will discuss how the business case for connected car apps is growing and, with open platform companies having already done the heavy lifting, there really is no barrier to entry.
Manufacturing connected IoT versions of traditional products requires more than multiple deep technology skills. It also requires a shift in mindset, to realize that connected, sensor-enabled “things” act more like services than what we usually think of as products. In his session at @ThingsExpo, David Friedman, CEO and co-founder of Ayla Networks, will discuss how when sensors start generating detailed real-world data about products and how they’re being used, smart manufacturers can use the data to create additional revenue streams, such as improved warranties or premium features. Or slash...
Akana has announced the availability of the new Akana Healthcare Solution. The API-driven solution helps healthcare organizations accelerate their transition to being secure, digitally interoperable businesses. It leverages the Health Level Seven International Fast Healthcare Interoperability Resources (HL7 FHIR) standard to enable broader business use of medical data. Akana developed the Healthcare Solution in response to healthcare businesses that want to increase electronic, multi-device access to health records while reducing operating costs and complying with government regulations.