Products
Technologies

Developer resources

Get a Client IP Address with a RemoteObject Call

Avg. Rating 4.4

Problem

Is there a way to restrict Flex 2 content and allow only internal network users or selected IP addresses access?

Solution

Yes. Using ColdFusion server-side logic, CGI.Remote_Addr, one can detect a User's IP address and limit access to a restricted part of Flex content.

Detailed explanation

Try It
MXML:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="getVisitorIP()" layout="vertical" backgroundColor="#8000FF" viewSourceURL="srcview/index.html">
    <mx:RemoteObject id="roUtility"
        destination="ColdFusion"
        source="flextraining.flexcookbook.components.utility"
        showBusyCursor="true">
        <mx:method name="getVisitorIP" result="getVisitorIP_handler(event.result)" fault="ro_fault(event)"/>
    </mx:RemoteObject>

    <mx:Script>
        <![CDATA[
            import mx.rpc.events.ResultEvent;
             import mx.rpc.events.FaultEvent;
            import mx.controls.Alert;
             import mx.utils.ObjectUtil;

            private var sIP:String;

            private function getVisitorIP():void {
                roUtility.getVisitorIP();
            }

            private function getVisitorIP_handler(result:Object):void {
                sIP = result.toString();
                lblIP.text = "IP: " + sIP
                if (sIP == "192.168.168.2") {
                       var u:URLRequest = new URLRequest("http://labs.insideflex.com/flextraining/jokesrus/jokeaday.html");
                    navigateToURL(u,"_blank");
                } else {
                    Alert.show("Sorry, access to this page is restricted...", "IP Address: " + sIP + " restricted");
                }
            }

            private function ro_fault(event:FaultEvent):void {
                // dump error message
                Alert.show(ObjectUtil.toString(event.fault));
            }
            
        ]]>
    </mx:Script>
    
    <mx:Label id="lblIP" text="IP:" color="white" />
</mx:Application>

CFC:
<cfcomponent name="utility" displayname="Utility CFC" hint="This component handles various utility-type interactions">
    <cffunction name="getVisitorIP" displayname="Get IP Address" hint="Returns Visitor's' IP address" access="remote" output="false" returntype="string">
        <cfset sIP = "#CGI.Remote_Addr#">
        <cfreturn sIP />
    </cffunction>
</cfcomponent>
Report abuse

Related recipes