views:

131

answers:

3

I have a template set up that I'm making ajax calls to via jQuery. I'm passing a URL parameter called "method" and then doing a <cfswitch> through each method to determine what block of code to execute.

Problem is, I don't want this page to be accessible outside of the ajax call. In other words, I don't want the template to run if someone just types the URL into their browser.

Is there a way to do that? I thought in .php there was a way to tell what type of request it was. Does anything like this exist in Coldfusion? Or any suggestions?

+7  A: 

jQuery injects the request with a X-Requested-With header set with the value "XMLHttpRequest". In coldfusion, you can view this by dumping the HTTP Request:

<cfdump var="#getHTTPRequestData()#">

So, all you need to do is test for that header, for example:

<cfset reqData = getHTTPRequestData()>
<cfif structKeyExists(reqData.headers,"X-Requested-With") and reqData.headers["X-Requested-With"] eq "XMLHttpRequest">
    Got an ajax request
<cfelse>
    <!--- do something else, or nothing --->
</cfif>
karim79
+5  A: 

If you're using CF8, "there's a function for that". :)

client side: use cfajax tags that populate view (i.e. cfdiv, cfwindow, cfgrid, cfinput...)

server side: use VerifyClient() on your .cfm template

OR:

client side: use <cfajaxproxy> to build JS to remote CFC proxy

server side: use <cffunction name="remoteMethod" access=remote verifyClient="true">

Henry
+1 for the bastardization of an Apple commercial
andrewWinn
and for a good answer
andrewWinn
I appreciate the advice with verifyClient(), I didn't know that! I've moved away from the built in ajax that coldfusion offers for jQuery. But I gave you a point up for a solid answer, I may end up having to use that some day. Thanks!
jyoseph
+1  A: 

None of this will truely protect you, it only stops the unmotivated, the motivated ones(haxors out there) could spoof any header that is included in the request trivially by using a browser plugin like Live HTTP Headers.

https://addons.mozilla.org/en-US/firefox/addon/3829

At best you will be left with little more than security by obscurity.

np0x
This is correct, but there's already a comment explaining the same thing, and the OP has responded that stopping the "unmotivated" is sufficient.
Daniel Pryden
I noticed that comment after starting my post, but felt there was still some value to reference the tool which is also helpful for debugging or testing in some cases as well as pointing out how easy it is to tweak headers these days.
np0x