0% found this document useful (0 votes)
187 views

Adobe ColdFusion 9 - Application-Based User Security Example

This document provides an example of implementing user authentication and authorization in a ColdFusion application. It includes three pages: Application.cfc handles authentication by checking for a logged in user, displaying a login form if needed, and authenticating credentials. loginform.cfm displays the login form. securitytest.cfm is a sample page that displays the user's roles if they are logged in. Application.cfc ensures a user is authenticated before other pages run and provides a logout link. Together these pages demonstrate basic user login and access control in ColdFusion.

Uploaded by

Art Longs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
187 views

Adobe ColdFusion 9 - Application-Based User Security Example

This document provides an example of implementing user authentication and authorization in a ColdFusion application. It includes three pages: Application.cfc handles authentication by checking for a logged in user, displaying a login form if needed, and authenticating credentials. loginform.cfm displays the login form. securitytest.cfm is a sample page that displays the user's roles if they are logged in. Application.cfc ensures a user is authenticated before other pages run and provides a logout link. Together these pages demonstrate basic user login and access control in ColdFusion.

Uploaded by

Art Longs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

AdobeColdFusion9

Productsupport

Search

Thisreferenceonly

ViewHelpPDF(23MB)

Home/DevelopingColdFusion9Applications/DevelopingCFMLApplications/SecuringApplications/
Implementingusersecurity

Applicationbasedusersecurityexample
Example:Application.cfc
Example:loginform.cfm
Example:securitytest.cfm
Thefollowingexampleshowshowtoimplementusersecuritybyauthenticatingusersandthenallowinguserstoseeoruseonlythe
resourcesthattheyareauthorizedtoaccess.
ThisexamplehasthreeColdFusionpages:
TheApplication.cfcpagecontainstheauthenticationlogicthatcheckswhetherauserisloggedin,requeststheloginpageif
theuserisnotloggedin,andauthenticatesthedatafromtheloginpage.Iftheuserisauthenticated,itlogstheuserin.
Thispagealsoincludestheonebuttonformandlogicforloggingoutauser,whichappearsatthetopofeachpage.
Theloginform.cfmpagedisplaystheloginform.ThecodeonthispagecouldalsobeincludedinApplication.cfc.
Thesecuritytest.cfmpageisasampleapplicationpage.Itdisplaystheloggedinusersroles.
TestthesecuritybehaviorbyaddingyourownpagestothesamedirectoryastheApplication.cfcpage.
TheexamplegetsuserinformationfromtheLoginInfotableofthecfdocexamplesdatabasethatisinstalledwithColdFusion.Youcan
replacethisdatabasewithanydatabasecontainingUserID,Password,andRolesfields.Thesampledatabasecontainsthefollowing
data:
UserID

Password

Roles

BobZ

Ads10

Employee,Sales

JaniceF

Qwer12

Contractor,Documentation

RandalQ

ImMe

Employee,HumanResources,Manager

Becausespacesaremeaningfulinrolesstrings,donotfollowthecommaseparatorsintheRolesfieldswithspaces.

Example:Application.cfc
TheApplication.cfcpageconsistsofthefollowing:

<cfcomponent>
<cfsetThis.name="Orders">
<cfsetThis.Sessionmanagement="True">
<cfsetThis.loginstorage="session">

<cffunctionname="OnRequestStart">
<cfargumentname="request"required="true"/>
<cfifIsDefined("Form.logout")>
<cflogout>
</cfif>

<cflogin>
<cfifNOTIsDefined("cflogin")>
<cfincludetemplate="loginform.cfm">
<cfabort>
<cfelse>
<cfifcflogin.nameIS""ORcflogin.passwordIS"">
<cfoutput>
<h2>YoumustentertextinboththeUserNameandPasswordfields.
</h2>
</cfoutput>
<cfincludetemplate="loginform.cfm">
<cfabort>
<cfelse>

<cfqueryname="loginQuery"dataSource="cfdocexamples">
SELECTUserID,Roles
FROMLoginInfo
WHERE
UserID='#cflogin.name#'
ANDPassword='#cflogin.password#'
</cfquery>
<cfifloginQuery.RolesNEQ"">
<cfloginusername="#cflogin.name#"Password="#cflogin.password#"
roles="#loginQuery.Roles#">
<cfelse>
<cfoutput>
<H2>Yourlogininformationisnotvalid.<br>
PleaseTryagain</H2>
</cfoutput>
<cfincludetemplate="loginform.cfm">
<cfabort>
</cfif>
</cfif>
</cfif>
</cflogin>

<cfifGetAuthUser()NEQ"">
<cfoutput>
<formaction="securitytest.cfm"method="Post">
<inputtype="submit"Name="Logout"value="Logout">
</form>
</cfoutput>
</cfif>

</cffunction>
</cfcomponent>

Reviewingthecode
TheApplication.cfcpageexecutesbeforethecodeineachColdFusionpageinanapplication.Formoreinformationonthe
Application.cfcpageandwhenitisexecuted,seeDesigningandOptimizingaColdFusionApplication.
ThefollowingtabledescribestheCFMLcodeinApplication.cfcanditsfunction:
Code

<cfcomponent>
<cfsetThis.name="Orders">
<cfsetThis.Sessionmanagement="True">
<cfsetThis.loginstorage="session">

<cffunctionname="OnRequestStart">
<cfargumentname="request"required="true"/>

Description
Identifiesthe
application,
enablessession
management,
andenables
storinglogin
informationin
theSession
scope.
Beginsthe
definitionofthe
onRequestStart
methodthat
runsatthe
startsofeach
request.

<cfifIsDefined("Form.logout")>
<cflogout>
</cfif>

<cflogin>
<cfifNOTIsDefined("cflogin")>
<cfincludetemplate="loginform.cfm">

Iftheuserjust
submittedthe
logoutform,
logsoutthe
user.The
followingcflogin
tagrunsasa
result.
Runsifthereis
nologgedin
user.
Teststoseeif

<cfabort>

theuserhas
submitteda
loginform.If
not,uses
cfincludeto
displaythe
form.Thebuilt
incflogin
variableexists
andcontainsthe
usernameand
passwordonlyif
theloginform
usedj_username
andj_password
fortheinput
fields.
Thecfaborttag
prevents
processingof
anycodethat
followsonthis
page.

<cfelse>
<cfifcflogin.nameIS""ORcflogin.passwordIS"">
<cfoutput>
<h2>YoumustentertextinboththeUserNameandPasswordfields.</h2>
</cfoutput>
<cfincludetemplate="loginform.cfm">
<cfabort>

Runsiftheuser
submitteda
loginform.
Teststomake
surethatboth
nameand
passwordhave
data.Ifeither
variableis
empty,displays
amessage,
followedbythe
loginform.
Thecfaborttag
prevents
processingof
anycodethat
followsonthis
page.

<cfelse>
<cfqueryname="loginQuery"dataSource="cfdocexamples">
SELECTUserID,Roles
FROMLoginInfo
WHERE
UserID='#cflogin.name#'
ANDPassword='#cflogin.password#'
</cfquery>

<cfifloginQuery.RolesNEQ"">
<cfloginusername="#cflogin.name#"Password="#cflogin.password#"roles="#loginQuery.Roles#">

Runsiftheuser
submitteda
loginformand
bothfields
containdata.
Usesthecflogin
structuresname
andpassword
entriestofind
theuserrecord
inthedatabase
andgetthe
usersroles.
Ifthequery
returnsdatain
theRolesfield,
logsintheuser
usingtheusers
nameand
passwordand
theRolesfield
fromthe
database.In
thisapplication,
everyusermust

beinsomerole.

<cfelse>
<cfoutput>
<H2>Yourlogininformationisnotvalid.<br>
PleaseTryagain</H2>
</cfoutput>
<cfincludetemplate="loginform.cfm">
<cfabort>

Runsifthe
querydidnot
returnarole.If
thedatabaseis
valid,this
meansthere
wasnoentry
matchingthe
userIDand
password.
Displaysa
message,
followedbythe
loginform.
Thecfaborttag
prevents
processingof
anycodethat
followsonthis
page.

</cfif>
</cfif>
</cfif>
</cflogin>

Endsthe
loginquery.Roles
testcode.
Endstheform
entryempty
valuetest.
Endstheform
entryexistence
test.
Endsthe
cflogintag
body.

<cfifGetAuthUser()NEQ"">
<cfoutput>
<formaction="securitytest.cfm"method="Post">
<inputtype="submit"Name="Logout"value="Logout">
</form>
</cfoutput>
</cfif>

Ifauseris
loggedin,
displaysthe
Logoutbutton.
Iftheuserclicks
thebutton,
poststheform
tothe
applications
(theoretical)
entrypage,
index.cfm.
Application.cfc
thenlogsout
theuserand
displaysthe
loginform.If
theuserlogsin
again,
ColdFusion
displays
index.cfm.

</cffunction>
</cfcomponent>

Endsthe
onRequestStart
method
Endsthe
Application
component.

Example:loginform.cfm

Theloginform.cfmpageconsistsofthefollowing:

<H2>PleaseLogIn</H2>
<cfoutput>
<formaction="#CGI.script_name#?#CGI.query_string#"method="Post">
<table>
<tr>
<td>username:</td>
<td><inputtype="text"name="j_username"></td>
</tr>
<tr>
<td>password:</td>
<td><inputtype="password"name="j_password"></td>
</tr>
</table>
<br>
<inputtype="submit"value="LogIn">
</form>
</cfoutput>

Reviewingthecode
Thefollowingtabledescribestheloginform.cfmpageCFMLcodeanditsfunction:
Code

Description
Displaystheloginform.

<H2>PleaseLogIn</H2>
<cfoutput>
<formaction="#CGI.script_name#?#CGI.query_string#"method="Post">
<table>
<tr>
<td>username:</td>
<td><inputtype="text"name="j_username"></td>
</tr>
<tr>
<td>password:</td>
<td><inputtype="password"name="j_password"></td>
</tr>
</table>
<br>
<inputtype="submit"value="LogIn">
</form>
</cfoutput>

Constructstheformactionattributefrom
CGIvariables,witha?characterpreceding
thequerystringvariable.Thistechnique
worksbecauseloginform.cfmisaccessedby
acfincludetagonApplication.cfc,sothe
CGIvariablesarethosefortheoriginally
requestedpage.

TheformrequestsauserIDandpassword
andpoststheusersinputtothepage
specifiedbythenewurlvariable.
Usesthefieldnamesj_usernameand
j_password.ColdFusionautomaticallyputs
formfieldswiththesevaluesinthe
cflogin.nameandcflogin.passwordvariables
insidethecflogintag.

Example:securitytest.cfm
Thesecuritytest.cfmpageshowshowanyapplicationpagecanuseColdFusionuserauthorizationfeatures.Application.cfcensures
theexistenceofanauthenticateduserbeforethepagecontentappears.Thesecuritytest.cfmpageusestheIsUserInAnyRoleand
GetAuthUserfunctionstocontroltheinformationthatisdisplayed.
Thesecuritytest.cfmpageconsistsofthefollowing:

<!DOCTYPEHTMLPUBLIC"//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>Securitytestpage</title>
</head>

<body>
<cfoutput>
<h2>Welcome#GetAuthUser()#!</h2>
</cfoutput>

ALLLoggedinUsersseethismessage.<br>
<br>
<cfscript>
if(IsUserInRole("HumanResources"))

WriteOutput("HumanResourcesmembersseethismessage.<br><br>");
if(IsUserInRole("Documentation"))
WriteOutput("Documentationmembersseethismessage.<br><br>");
if(IsUserInRole("Sales"))
WriteOutput("Salesmembersseethismessage.<br><br>");
if(IsUserInRole("Manager"))
WriteOutput("Managersseethismessage.<br><br>");
if(IsUserInRole("Employee"))
WriteOutput("Employeesseethismessage.<br><br>");
if(IsUserInRole("Contractor"))
WriteOutput("Contractorsseethismessage.<br><br>");
</cfscript>

</body>
</html>

Reviewingthecode
Thefollowingtabledescribesthesecuritytest.cfmpageCFMLcodeanditsfunction:
Code

Description

<cfoutput>
<h2>Welcome#GetAuthUser()#!</h2>
</cfoutput>

ALLLoggedinUsersseethismessage.<br>
<br>

<cfscript>
if(IsUserInRole("HumanResources"))
WriteOutput("HumanResourcesmembersseethismessage.<br><br>");
if(IsUserInRole("Documentation"))
WriteOutput("Documentationmembersseethismessage.<br><br>");
if(IsUserInRole("Sales"))
WriteOutput("Salesmembersseethismessage.<br><br>");
if(IsUserInRole("Manager"))
WriteOutput("Managersseethismessage.<br><br>");
if(IsUserInRole("Employee"))
WriteOutput("Employeesseethismessage.<br><br>");
if(IsUserInRole("Contractor"))
WriteOutput("Contractorsseethismessage.<br><br>");
</cfscript>

Displaysawelcomemessagethatincludes
theusersloginID.

Displaysthismessageinallcases.Thepage
doesnotdisplayuntilauserisloggedin.

Testswhethertheuserbelongstoeachofthe
validroles.Iftheuserisinarole,displaysa
messagewiththerolename.
Usersseeonemessageperrolethatthey
belong.

TwitterandFacebookpostsarenotcoveredunderthetermsofCreativeCommons.

Home/DevelopingColdFusion9Applications/DevelopingCFMLApplications/SecuringApplications/
Implementingusersecurity

LegalNotices|OnlinePrivacyPolicy

You might also like