ColdFusion 9.0 Resources Developing ColdFusion 9 Applications |
Web server–based authentication user security exampleThe following example shows how to implement user security using web-server–based basic authentication and two roles, user and administrator. This example has two ColdFusion pages:
This simple example does not provide a user log-out interface. Test the security behavior by adding your own pages to the same directory as the Application.cfc page. Example: Application.cfcThe Application.cfc page consists of the following: <cfcomponent> <cfset This.name = "Orders"> <cffunction name="OnRequestStart"> <cfargument name = "request" required="true"/> <cflogin> <cfif IsDefined("cflogin")> <cfif cflogin.name eq "admin"> <cfset roles = "user,admin"> <cfelse> <cfset roles = "user"> </cfif> <cfloginuser name = "#cflogin.name#" password = "#cflogin.password#" roles = "#roles#" /> <cfelse> <!--- This should never happen. ---> <h4>Authentication data is missing.</h4> Try to reload the page or contact the site administrator. <cfabort> </cfif> </cflogin> </cffunction> </cfcomponent> Reviewing the codeThe Application.cfc onRequestStart method executes before the code in each ColdFusion page in an application. For more information on the Application.cfc page and when it is executed, see Designing and Optimizing a ColdFusion Application. The following table describes the CFML code in Application.cfc and its function:
Example: securitytest.cfmThe securitytest.cfm page shows how any application page uses ColdFusion user authorization features. The web server ensures the existence of an authenticated user, and the Application.cfc page ensures that the user is assigned to roles the page content appears. The securitytest.cfm page uses the IsUserInAnyRole and GetAuthUser functions to control the information that is displayed. The securitytest.cfm page consists of the following: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Basic authentication security test page</title> </head> <body> <cfoutput> <h2>Welcome #GetAuthUser()#!</h2> </cfoutput> ALL Logged-in Users see this message.<br> <br> <cfscript> if (IsUserInRole("admin")) WriteOutput("Users in the admin role see this message.<br><br>"); if (IsUserInRole("user")) WriteOutput("Everyone in the user role sees this message.<br><br>"); </cfscript> </body> </html> Reviewing the codeThe following table describes the securitytest.cfm page CFML code and its function:
|