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:

<cffunction name="getDate"
<cfreturn #now()# />

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);

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" />
<cfif isDefined("cflogin")>
<cfif eq "someUsername" and
cflogin.password eq "somePassword">
<cfloginuser name=""
roles="admin" />

That’s all you have to do.