Using cflogin with Flash Remoting

I did a session on Flash Remoting with ColdFusion at Flashforward here in San Francisco, and I got a pretty good question from someone in the audience. He wanted to know how to use ColdFusion’s built-in authentication mechanism with ColdFusion components and Flash Remoting. Fortunately, ColdFusion and Flash make it very easy.

First of all, CFC functions have an optional “roles” attribute which you can use to limit access to that specific function. So the first thing you do is specify a coma-delimited list of roles which are valid for your function. The example function I wrote is below:

<cfcomponent>
<cffunction name="getDate"
access="remote"
roles="admin"
returnType="date">
<cfreturn #now()# />
</cffunction>
</cfcomponent>

The next thing you do is use the setCredentials function on a NetConnection instance in ActionScript. Example code below:

var gw = "http://localhost/flashservices/gateway";
var con = NetServices.createGatewayConnection(gw);
// username and password are text fields...
con.setCredentials(username.text, password.text);
var serv = con.getService("com.macromedia.tests.auth_test", this);
serv.getDate();

The last thing you have to do is map your username and your password to one or more roles, which you do using cflogin and cfloginuser. I put the following code in an example Application.cfm file:

<cfapplication name="authTest" />
<cflogin>
<cfif isDefined("cflogin")>
<cfif cflogin.name eq "someUsername" and
cflogin.password eq "somePassword">
<cfloginuser name="#cflogin.name#"
password="#cflogin.password#"
roles="admin" />
</cfif>
</cfif>
</cflogin>

That’s all you have to do.