Flex / AIR, PHP and user authentication

So you’ve built a Flex or AIR application that talks to a PHP server and you’re wondering how to authorize users? Actually, it is very easy to do this. You can do the same things you would do with a PHP web application: authenticate the user credentials, start a session and write some session values. Then, for any subsequent calls, first you check if the session values are set to determine if the user is logged in. This approach works in the same way for a Flex application deployed on the browser or deployed on the desktop (an AIR application), because once the server starts a session and sends the response back to the client, Flash player adds the session ID to any other call made to the same server (of course the calls must use HTTP or HTTPS).

So let’s recap what happens:

  1. The Flex client (could be a web app or an AIR app) makes a request to a PHP file to authenticate the user: http://localhost/login.php
  2. The “login.php” validates the user and if successful it starts a session and saves to the session some variables regarding the authenticated user
  3. The server sends a response back to the Flex client
  4. The Flex client makes new HTTP/HTTPS requests to the same server. The session id is appended to the request
  5. The PHP server scripts called from the client use the same session and they can retrieve from the session any info that was saved by “login.php

Another way to handle the authentication is by using a token. The workflow is:

  1. The Flex client sends user credentials to the server
  2. If the user credentials are correct, the server sends back a token that is unique for the given user
  3. From that point on, whenever the Flex client makes a request to the server, it sends the token too.

Why should you use a token instead of relying on the session mechanism? I don’t think one method is always better than the other, it really depends on your architecture and your specific needs. For example if you use the token approach, you have two advantages: you don’t care about session expiration time and you don’t care about the server domain (for example you could have more domains sharing the same user database and using the token approach you don’t need to authenticate on each domain in order to start a session). On the other hand, using the session approach could be better if you can leverage existenting applications on the server side, or you don’t want the token appended to each request you make from Flex application.

I put together a simple Flex application to illustrate how you can authenticate from Flex on a PHP server. You can download the app from here and you can import the archive in Flex Builder using Import > Flex Builder > Flex project. Inside of the project is a folder “user_auth“. You should move this folder to your PHP web server and then you need to change, in the MXML file, the value of SERVER_URL constant. It should be the correct URL for your setup (it is defined right at top of the MXML file). On my computer, the constant has this value http://localhost/user_auth/. As a side note, this code works as well as an AIR application, just create an AIR project and copy the script code and the services/UI components into the MXML file and you are done.

The calls to the PHP server are made using either HTTPService or RemoteObject (I am using AMFPHP on the server side). If you run the application, you will see three areas with buttons: one for authentication using session and HTTPService, one for token authentication using HTTPService, and the last one for using RemoteObject and session. One way to test it is: open the the application in Firefox and click on the first button, a session will be started on the server and some values will be set in the session. If you open the same application in Safari (or any browser other than the one you just used) and click on the second button (Make Request to another page which…) you will get an error as the PHP script checks that some specific values are set in the session.

If you want to try the “Authenticate against LDAP” workflow, first you need to be able to access a LDAP server from the PHP server and you need to open the “ldap_auth.php” PHP file and set the correct values for RDN, DN, and hostname.

34 thoughts on “Flex / AIR, PHP and user authentication

  1. Pingback: Flex / AIR, PHP and user authentication « Rich Internet Applications

  2. What would be the best method for showing certain Flex app elements based on user permissions in a DB (MySQL)? Say, admins can see a delete button and regular users cant, but can see everything else.

    Thanks,
    Dan

  3. One way is to set the visible property to “false” on the UI Components you want to hide.

    Another way is to use mx:states to define one state for each rol.

  4. By that method though, if someone took the SWF file and decompiled it, wouldn’t they see items that they could use maliciously?

  5. Yes, they can decompile and see the buttons they shouldn’t, but they cannot use it. As I explained in my post, when the client make a request to the server, the server knows (based on session or token) what user / credentials made the request. If the method is outside of the user rol, it is discarded.

  6. I am using only HTML/Javascript to develop my AIR application. I was unable to get your project imported in Aptana.

    I am trying to understand how to save tokens with AIR. Are they simply string variables ? In the server-side code,, does each user have a different token? What’s the best approach for generating tokens ?

  7. @seme1
    1. To import the project you need to have Flex Builder 3

    2. Usually a token is a string of 32 chars or more. Each user must have an unique token, and many people are generating using a hash function such as MD5.

  8. Pingback: Bookmarks about Air

  9. Hi there,

    Been trying to create a user authentication using Flex 3 and AMFPHP. What happens in my case is that the PHP function works in the service browser, but when i try to pass variables into the PHP function (using remote object), either the variables are not being passed in or the PHP function is not returning the variable i need for other checking purposes.

    Just a few questions after reading the tutorial:
    1) Is it necessary to use the AsyncToken for user authentication?
    2) What kind of data does AMFPHP pass back to Actionscript?

    Thanks in advance for the help.

  10. @avidFlex
    >>1) Is it necessary to use the AsyncToken for user authentication?
    I am not sure I understood your question. If you use RemoteObject (with AMFPHP) you have just to register the listners for result to receive the answer from the call.

    >>2)What kind of data does AMFPHP pass back to Actionscript?
    Here is a resource to see the mapping between the ActionScript types and PHP: http://amfphp.org/docs/datatypes.html

    Take a look at my article on Flex and PHP with AMFPHP http://corlan.org/2008/10/10/flex-and-php-remoting-with-amfphp/

  11. Hello,

    I’ve developed Flex Air application that consumes Web services on telephony server. I’ve added Authorization header to enable Basic http authentication; the problem I have is that “someone” (Flex Air engine?) asks for security certificate every time the Web service is invoked. I can’t force the application to import the certificate (in “Security Alert” window it says “The import was successful”, but next time when the service is invoked, it is the same story). The service returns valid result.

    Application written in C#, which consumes same Web service with same credentials and on same client workstation works fine.

    Any idea how to proceed?

    Thx,
    Dejan

  12. @Dejan
    I think the problem is with the certificate. If this is a certificate signed by Certificate Authority, it shouldn’t ask every time. Otherwise, if you try the same thing but in the IE browser, I think will ask for permission each time.

  13. I have read this page …

    http://www.amfphp.org/docs/authenticate.html

    and the example given there uses Flash. You have given an example for Flex (just like your “remoting with amfphp” article).

    I guess the correct approach would be to put forward my specific case before asking:

    I want to make a desktop AIR application which authenticates against the user’s account residing on a mysql database on the website server before letting him/her use the application. Am I making sense? lol.

    1. What should I use – Flex or Flash – to make the app?
    2. Will it work the same either way? How different the approach/coding would be?

    I have to make a choice between flex and flash. If an AIR app cannot be made to do what I want then I would have to take the flex route. I would really appreciate it if you help me out.

  14. @Sumeet

    Yes you can apply these to an AIR app. In fact I state this in my article.

    It is not a good idea in an AIR application to rely on authentication only on the server side. If you code that way your application, then if the user doesn’t have Internet access or your server is broke, he can not use the AIR app.

    Regarding Flash vs Flex, there is not an absolute resolution here. I prefer Flex. And in generally if you have to do an enterprise app, or an application that manipulates a lot of data, then probably Flex is the choice to go.

    Good luck with your project!

  15. Thanks for the reply Mihai :)

    “Yes you can apply these to an AIR app. In fact I state this in my article.”

    Yes, I know you said the AMFPHP thing works in an AIR app. But your article is about a Flex-AIR combo, not Flash-AIR. So, I wanted to know if I can connect to the MySQL database on the website from my “AIR desktop app made in Flash (not Flex)”. Just clarifying.

    “if you have to do an enterprise app, or an application that manipulates a lot of data, then probably Flex is the choice to go.”

    My application is not data-heavy and is more tutorial-like and I want it to be more beautiful than number crunching capable. And that is precisely why I want to use Flash because I would go mad skinning in Flex and I would have to lean on big brother Flash to help me out anyway with the look of my app. So I do not want to get into Flex as it would be like learning to use a bulldozer to knock off a flowerpot.

    “It is not a good idea in an AIR application to rely on authentication only on the server side. If you code that way your application, then if the user doesn’t have Internet access or your server is broke, he can not use the AIR app.”

    So what should I do? I want it subscription based not license based. And anyways apps like SHIFD use user authentication to get into the app, so why not me?

    Would be waiting for opinion. Thanks again for the help. REALLY appreciate it.

  16. I probably know the answer to this, but how bad is it to write the token to the html page with php? This would happen on the pages after the user has logged in that contain flash components.

  17. @Renuka

    You go to Preferences > General > Linked Resources

    and you add these two variables; PHP_WEB_URI pointing to the root URL and PHP_FLEX_SERVER_ROOT to absolute path of the web server

  18. Hello,

    I am trying to get an AIR app to authenticate with a form which is in aspx. I send a urlrequest for a file and it comes back with a redirect. I then send the username and password along with the correct url which was the original redirect. It is supposed to supply a cookie which authoizes the request but I never see the cookie in although docs say cookies are maintained automatically.

    Thanks

  19. Hi Mihai,

    First of all, thank you very much for the useful article! It shed some light on questions I didn’t have answers to.

    I was wandering if you could elaborate a bit on the following scenario.

    I have a website managed by a CMS (Joomla), which I use as a wrapper for a Flex application. The user logs in using the built-in login facility. This way the ‘authenticated’ session is started by the browser. Now, the user starts the Flex app … and my question is does the Flash player automatically capture the authenticated session from the browser or it starts a new session? In addition, how can I check in the Flex application if the user has logged in successfully, given the authentication happens in the browser?

    I would be very grateful if you could at least give me a hint on these questions.

    Cheers,

    Naso.

  20. @Naso

    Once a session was started, Flash Player appends automatically the session id to any request to the server.

    You can check in Flex that the user is authenticated by making a request to the server (remoting/httpservice). The requested page can send back true or false depending on the user authentication state.

  21. So, what’s the difference between tokens and sids? Hm? Don’t u think it’s kind a same thing.
    As u authorize the client on the server-side, u process the SID to the client and every next client request carries the SID for re-authorization. To add, SIDs are unique for every user. So, to sum, tokens === SIDs.
    Ain’t i’m right, am? Or it’s just that i got u wrong?

  22. A nice article with various ways of authenticating users with PHP…

    A small correction in PHP Code [ldap_auth.php:Line 29]:
    Wrong Code: [@ldap_set_option($ldapConn, ‘LDAP_OPT_PROTOCOL_OPTION’, 3);]
    Correct Code: [@ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);]

    After the change it is working fine. Thanks :)

  23. @Bartosz Kosarzycki

    You shouldn’t use MD5 for passwords anymore. It is not safe. Take a look at Hash engine for PHP instead.

  24. Hi,

    I have been learning the flex for more than a week now and started using flex 4.5 for php.

    I wanted to implement a login and authentication in my app and I followed yours patter. i downloaded your code and imported. It worked fine though it was of flex 3.

    Now when I want to reuse your code in my application (Web not AIR), I copied the log.txt, myServices.php to libraries and amended my main.mxml from your mxml.

    But your mxml has only one name space defined mx and my mxml has by default threes, fx and mx so there were clashing of namespaces. I through trial and error and thriugh what learned a bit removed. But the HTTpService and remote object are generating errors i dont understand.

    I tried to look up in ADC and other resources.

    Could you help or put up a code for flex 4.5.

    With best regards

  25. Its giving
    ‘HTTPService’ declaration must be contained within the tag since it does not implement ‘mx.core.IUIComponent’ in Main.mxml

    Please guide

  26. I got It. I didnt paid attention to basic and ans was hidden in basicstructure of Mxml file.

    Thnks for sharing your code.

  27. Hi,
    First thank you for a great tutorial, very useful!!

    I have a standalone projector program which connects to a remote ms sql server on a remote iis server. i would like to allow windows authentication to an active directory domain. is it possible to do impersonation with a amf php??I have been able to do this with a php script running with the browser but not through my app. it there a way to this this automatically? or a way to get the access token after a computer logs in to the domain and attach it to requests made?

    any help would be great.

    thanks,

    Maor

  28. Hi Mihai, this is very useful, but before I use it, I have a doubt: Does this works on a Flex Mobile application that runs on AIR?

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *