User Guide
Example of User Authentication and Authorization 363
Example
The following example reads a protected file because the ColdFusion user pfoley has
been granted access to the file by the security context MyContext. If the user cannot
be authenticated, ColdFusion throws a Security exception.
<cfimpersonate securitycontext="MyContext"
username="pfoley"
password="admin"
type= "CF"
throwonfailure= "Yes">
<cffile file="#readFile#" action="read" variable="text">
<cfoutput>
The file contains the following text:<br>#text#<br>
</cfoutput>
</cfimpersonate>
Example of User Authentication and Authorization
The following sample pages illustrate how you might implement user security by
authenticating users and then allowing users to see or use only the resources that
they are authorized to use.
In this example, a user requests a page in an application named Orders, which is part
of a security context, also named Orders, that governs pages and resources for an
order-tracking application.
User security is generally handled in two steps:
1 The Application.cfm page checks to see whether the current user is
authenticated. If not, the page presents a login form and the user must submit a
username and password for authentication.
If the user passes the authentication test, ColdFusion passes the
cfauth cookie to
carry the user’s authentication state to subsequent application pages governed
by this Application.cfm page.
2 Only authenticated users can access the requested application page for selecting
and updating customer orders in a database. This page checks to see which
resources the authenticated user is authorized to see and use.
Authenticating users in Application.cfm
The following example code for an Application.cfm page checks first to see whether
the current user is authenticated by checking to see whether a login form was
submitted. If the username and password can be authenticated for the current
security context, the user passes through and the requested page is served.
If the Application.cfm page does not receive the user’s login information from the
previous page, it prompts the user to provide a username and password. The user’s