Firefox, Flex URLRequest, and Sessions Issue

I ran into a very difficult issue trying to get upload files using FileReference and URLRequest.  File upload was working fine in Internet Explorer, but nothing would work in Firefox.    I tried tracing out the request using LiveHTTPHeaders for Firefox, but I couldn’t even see any of the request data.    With some help from my co-worker we determined that Firefox was not sending the session with the file upload and was producing a login error.  On IE the session cookie is picked up and the upload request uses the authenticated session, no login error.   

Firefox apparently uses another instance of the browser window to dispatch the uploaded file, this window does not have the session.  I searched for some possible answer and it seems you need to ask the correction combination of questions to find the solution.   The Flex documentation seems to hint at part of the issue, but nothing direct enough.

Flex Livedocs:

The FileReference and FileReferenceList classes also do not provide methods for authentication. With servers that require authentication, you can download files with the Flash® Player browser plug-in, but uploading (on all players) and downloading (on the stand-alone or external player) fails. Listen for FileReference events to determine whether operations complete successfully and to handle errors.

So we know that authentication is not being passed along, so what can we do about it.   Searching for information related to URLRequest and sessionid revealed a good Flexcoders post on the same issue.   You need to add the session to the URLRequest (in our case we added the jsessionid for TomCat):

var request:URLRequest = new URL Request("http://www.[your url].com" + ";jsessionid=" _yoursessionid);

This was a bugger of a problem to solve and not an easy one to track down.  Our first reaction to the problem was that it was the JSP page or missing form data within Flex.  Then of course people start point figures at Flex in general as not having the ability to do simple form posts or upload.    It only appears if you are handling authentication when you upload files to the server.    I have read several post about the issue with uploading files with IE that work, but that fall down with other browsers.  Unfortunately, the information is not covered well by Flex documentation.  Thank goodness for Flexcoders, they have saved me a lot of grief.  However, not knowing this was a problem with authentication, I spent a lot of valuable time wrestling with the issue.  

70 Comments

  1. Hi,
    The flex doc says “FileReference and FileReferenceList classes also do not provide methods for authentication”. Does this mean that the request will not send the cookies along with the request?? Is this the same case with URLRequest?? A browser is suppose to implement cookies by spec. Does not the flex runtime conform this??
    Anyother ways to send cookies with request in flex??

  2. Thanks Michael for ur faster reply:)
    What I learned from the flexcoder post is that the jsessionid is not passed as a url parameter. You have to get it using getRequestedSessionId() and use it to authenticate. Right?
    I am using a custom authentication token instead of jsessionid. Already I am having code at server side, to authorize the token in the cookie coming with the request. Hv to retain this code for the jsp pages. Do I need to duplicate the implementation as in the flexcoder post to work with flex??

  3. I am having the same problem, but I am using PHP. PHP expects a cookie named PHPSESSID. Since Firefox is sending the request from a separate window/process, it is using a different cookie value than the main window (the one that has been authenticated.) Passing the parameter PHPSESSID in the URL/URLVariables does not seem to work. The server is still receiving the cookie.
    I am looking into other ways of solving the issue.

  4. I had the same problem when uploading files to our server using SWFUpload at http://www.arttoframes.com.
    It took about 2 minutes to figure it out with the Tamper Data plug into firefox. I would use firebug now, it has the same feature.
    Since we use our own custom session mechanism in PHP we were able to append the session id to the URL and it was picked up, this setting is specific for the upload page only. Passing session info in the url is considered a security risk by some.
    If i remember correctly a session id was being sent by flash but it was the wrong one.

  5. I recently went through this same discovery, but when I promoted my code, was getting reports of another, more subtle error. I’d love to know if anybody has solved it!

    1. User logs in, gets jsessionid=42.
    2. User uploads file using Flash, which automatically appends the sessionid onto the url.
    3. User waits until session timeout, then tries to upload again. Server returns authentication error, but creates ANOTHER sessionid (say, 13) which Flash remembers.
    4. User re-logs-in and gets one more sessionid (say 24), and tries uploading the file once more with . Flash appends 24 to the request, but also sends 13 as a “cookie” on the request.
    5. The server takes the “cookie” value before the URL parameter, and so barfs again.

    I need to figure out how to wipe the “cookie” value before uploading the file. Any ideas?

  6. Maybe you can call JavaScript on the page to clear the cookie, try ExternalInterface to create/call JS from Flex before upload.

  7. I think you’ve misdiagnosed this problem. It is true that the Flash Player does not send cookies in some browsers. This breaks sessions for most web apps. You can work around this by sending the session id in an alternate way (in the query string).

    However, the documentation discussing “authentication” is not referring to cookies and sessions. It is referring to HTTP authentication. When a server requires HTTP auth it will return a 401 status code and the browser will pop up a log in box. Flash/Flex does not support this. This is not a bug just a limitation.

    Not sending cookies is bug though.

  8. hi guys,
    i am new to flex i am now using the flex
    taglibrary to embed my mxml in to jsp . my problem i want to send the data i get from the textfield mxml application to another jsp page . i am using URLRequest, but i dont know how to send the parameters to next page using jsp using POST methos and how can i get the data in my second jsp page

    thanks
    kandasami raja
    kandaraja@gmail.com

  9. Hi,

    I’m facing the same problem. And appending jsessionId to the request doesn’t completely help (just as flexcoders page mentioned). I was getting the login errors when trying the upload (with jsessionId being passed correctly) and then a restart of the browser fixed the prob.

    I can see errors in my logs which indicates my users are facing these errors too many a times. Does anybody have a solution?

  10. Nishant,
    I have the same problem. I also have authentifiation problems in my upload requests. After a while, and when you have changed session (session expired or server restart), firefox starts to use the jsessionid stored in the cookie and doesn’t use the one passed in the url !

  11. Well, I’m stuck then coz I can’t clear my cookies. I use them in a lot of places. Maybe this is a solution, passing cookie instead if jsessionid in the upload URL. I’ll give this a try too.

  12. Thanks a lot Michael for this post.
    It solved a two day debugging session. I have had problems to integrate swfuplaod an JBoss Seam because of this nasty “wrong session issue”.

    Best regards,

    Frank

  13. Just user url varaiables in flex
    add the
    var url:urlVariables
    add the url varaiables to your urlReqest
    urlRequest.data = urlVaraiables;

    and then urlRequest.method = “POST” ;

  14. I’m not very good with Flex, I’m only using it for an upload app. that looks nice, and can upload multiple files at once, the rest of the site is still php. How would I get Flex the PHPSESSID to pass back to the upload.php file I have? Any code examples would be appreciated, thanks.

  15. I am working on a file uploader for our site, that will let users upload images of robots that they are wanting to sell. I wanted to let them upload more than one image, then when they submit the form we get a list of the images they uploaded. We also check to make sure there is not an image with the same name. If so we append -1, -2 etc… So to let the flex app know what the true url to the renamed image is I set session cookies with php. Everything worked great in IE. I tried it in firefox and nothing… after searching adobe, and google I came across this post. Here is my fix. When the program loads I check for a few cookies, they are used if the user has submited a contact form before, if so it used the cookies to fill in the required fields in the form. Well in the php I added this to the array of cookies…

    PHP CODE
    $cookieArray = array(“value1″=>$cookie1,”sid”=>session_id());

    I then have an invisable text line in the flex app named sid, so in flex I put this in the code,

    AS3 Code
    sid.text = cookieArray[0][‘sid’];

    then when I call on the upload script I used this.

    AS3 Code
    var endpoint:String = “pathToUploadScript.php?sid=” + sid.text;

    Then on the upload script page i added this to the top, just under the session_start();

    PHP CODE
    if(isset($_GET[‘sid’])){
    session_id($_GET[‘sid’]);
    }

    Now my uploader works great in Firefox, and IE.
    I have found other solutions to this but this was far much easier and faster. Hope this can help someone that is using flex, php.

    1. Thanks, my problem was solved passing the session id back to php
      And in php I do as follows:

      session_id($_POST[‘sid’]);
      session_start();

      Hope this help others

  16. I’m not quite sure if you have the same “problem”
    but when uploading with flex the SERVER generates a new SESSION ID =/ for the upload

    call it a bug if you want… but it’s a pain in the a.. for sure

  17. having the same darn issue with Firefox . After the uploader is gone, I am logged out. Tried saving the session and assigning it as a new session_id($newsession) but that did not work.

    So weird

  18. FileReference loose cookies but you can avoid this bug if you don’t send “pragma: no-cache”

    In my case, to override what doing Tomcat, I create a J2EE filter doing this:
    response.setHeader(“Pragma”,””);

    Currently, I use Tomcat with Realm Authentication and FileReference can upload nicely in HTTP.

    FileReference can’t be used to upload in HTTPS with firefox.
    The workaround is to use an standard HTML form with Javascript/DOM mud (with ExternalItnerface).

  19. It solved a two day debugging session. I have had problems to integrate swfuplaod an JBoss Seam because of this nasty “wrong session issue”.

  20. Hi JASON S,

    Thanks for the info. But the problem is I’m new in flex. How can i do that. can u provide some examples with source codes? Thanks in advance!

  21. We’ve had the same problem with this too. We solved it by reneweing the cerificate on our website of our server.

  22. To solve session issue in PHP I dont call session_start() in script that process upload request, so to you keep your script safe, make another security check, with a hash for instance

  23. I have to same problem but just with flash FileReference and PHP (don’t us Flex)

    Same thing; upload works in internet explorer but not in firefox. Which is still not really problem since most still use Explorer.
    But I don’t lose my session. It goes likes this; Flash could call getXMLData.php (session present) -> upload.php (session gone)-> getXMLData.php (session present)

    But is calling fileRef.upload(“processupload.php?sessionid=” + sessionid) with the sessionid safe?

  24. True. i used to be a musician for over 15 years – but than i figured out someday that making some money would also be nice. So i changed the industry. I´wwouln´t be able to do a 9 to 5 job with a boss watching over me and everything strictly regulated. So i still do my own stuff, not THAT creative anymore but alos in my new job i try to to it my own way…and it works. Creativity ist the echo of life in ourselve… we should never loose it.

    1. This would most likely be passed back to you on the payload when you make a login call using a web service like JSON. But this depends on how you setup your web services.

  25. hi ,
    I am new to flex I wanted to know how we can manage session time out in Flex i need to know how we can time out a session if user isnt interating,,,he should be timed out automatically

  26. I experience this issue on firefox. Any fixes by adobe for the flash player on firefox 3.0.6? Shockwave Flash Plugin 9.0 r115

  27. OMG. I think you did save my day(s).

    I don’t know it’s gonna works or not. But now I’d seen IE works.

    Thank you. =)

  28. I had the same problem, but appending the session id to the url didn’t work.
    Luckily AS3/Flex has the URLRequestHeader component, which works quite well.

    To get the cookie from AS3:
    [as]
    public var cookieStr:String;
    public var cookieHeader:URLRequestHeader;

    ExternalInterface.call(‘eval’,’window.cookieStr = function () {return document.cookie};’)
    cookieStr = ExternalInterface.call(‘cookieStr’);
    cookieHeader = new URLRequestHeader(“Cookie”,cookieStr);
    [/as]

    Then when you’re using your URLRequest object:
    [as]
    var urlRequest:URLRequest;
    urlRequest = new URLRequest(… blah blah, url here, etc etc);
    urlRequest.requestHeaders.push(cookieHeader);
    [/as]

    Hope this helps somebody 🙂

    1. Well, this seems not working even with the newest Flash player. I’m using 10+. I’ve tried to call an URLLoader along with the URLRequest set with URLRequestHeader, but the compiler thrown error as “#2096: The HTTP request header Cookie cannot be set via ActionScript.”. Any idea?

    2. Im working on a project where i need to read the session id from the cookie of a http request from the Adobe Air application.
      I have found a property called URLRequest.manageCookies supported by AIR so i Hope there should be a way to read the cookies as well.
      Im Using Flash Builder 4.5

      I want to read http cookies not Local shared Object and not in a web broser in a desktop application.
      Please provide if you have any reference

  29. Looking at Perlin’s comment’s but perlexed:

    That method produces:
    ArgumentError: Error #2096: The HTTP request header Cookie cannot be set via ActionScript.
    at flash.net::URLStream/load()
    at flash.net::URLLoader/load()

    Compiling using Flex Builder 3.

    Why?

    Have done some research and found that not allowing this is secruity feature in newer flash players:
    From.. : http://www.securiteam.com/securityreviews/5KP0M1FJ5E.html


    In Flash 9, the techniques described above (for the LoadVars class) do not work for any browser-provided header (e.g. User-Agent, Host and Referer), nor probably for many “protected” headers such as Content-Length. Still, headers like Expect can be sent, so some attacks (e.g. Example 1 above) are still effective with Flash 9.

  30. Yep, found that out too a bit later on. My project was for a closed LAN and it worked perfectly (I’m guessing Flash player assumes local IPs are “trusted” or some such). I’ve been trying to fool it into thinking any IP is trusted but no luck. My only other guess would be to develop some sort of “proxy” script using the session-id-on-url trick that then hands the data over to the ‘s authentication and uploading system.

    In the system I used (JAWS CMS) it gets the session ID exclusively from the cookie, so the GET trick won’t work, ergo a proxy script is the best bet.

    Best of luck!

  31. In Flash 9, the techniques described above (for the LoadVars class) do not work for any browser-provided header (e.g. User-Agent, Host and Referer), nor probably for many “protected” headers such as Content-Length. Still, headers like Expect can be sent, so some attacks (e.g. Example 1 above) are still effective with Flash 9.

  32. i managed to work around this bug using flex and java web filter

    Flex Code :

    var urlVars:URLVariables = new URLVariables();
    urlVars.jsessionid = sessionID;

    var uploadUrl:String = “http://localhost:8080/mywar;jsessionid=”+sessionID;
    uploadUrl += “?”+getClientCookies(); //put all client cookies on the query string
    var urlRequest:URLRequest = new URLRequest(uploadUrl);
    urlRequest.method = URLRequestMethod.POST;
    urlRequest.data = urlVars;

    //will go first time and get the cookies set see flex docs
    var testUpload:Boolean = true;
    fileRef.upload(urlRequest,”Filedata”,testUpload);

    JAVA CODE :

    package com.mywar.fileupload;

    import java.io.IOException;
    import java.util.Enumeration;

    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    * @author orasio – spieler
    * This filter comes to solve the Firefox ,Chrome and SAFARI file upload issue
    * The problem was that the file uploaded by the flex
    * FileReference came with a different session and no cookies
    * To solve this problem do the following :
    *
    *
    * don’t forget to add this filter to the web.xml file
    */
    public class FileUploadFilter implements Filter {

    private static final String CONTENT_LENGTH = “content-length”;
    private static final String UPLOAD_SITE_PATH = “/”;
    private static final String JSESSIONID = “JSESSIONID”;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request,
    ServletResponse response,
    FilterChain filterChain)
    throws IOException, ServletException {
    if ((request instanceof HttpServletRequest)
    && (response instanceof HttpServletResponse)) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    //httpRequest.getHeader(“user-agent”); //Shockwave Flash
    String contentLength = httpRequest.getHeader(CONTENT_LENGTH);
    boolean isFlexTest = (contentLength!=null
    && Integer.parseInt(contentLength)==0);
    if(isFlexTest){
    HttpServletResponse httpResponse =
    (HttpServletResponse) response;
    setAllClientCookie((HttpServletResponse)response, httpRequest);
    PrintWriter out = httpResponse.getWriter();
    out.println(“OK”);
    out.close();
    return;
    }
    }
    filterChain.doFilter(request, response);
    }

    /*
    * write all cookies back to the flex test response
    */
    @SuppressWarnings(“unchecked”)
    private void setAllClientCookie(HttpServletResponse httpResponse,
    HttpServletRequest httpRequest) {
    Enumeration parameterNames =
    (Enumeration)httpRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
    String cookieName = (String) parameterNames.nextElement();
    //since we get IllegalArgumentException: Cookie name “JSESSIONID” is a reserved token

    if(!cookieName.contains(JSESSIONID)) {
    Cookie cookie =
    new Cookie(cookieName, httpRequest.getParameter(cookieName));
    cookie.setPath(UPLOAD_SITE_PATH);
    httpResponse.addCookie(cookie);
    }
    }
    }

    @Override
    public void destroy() {
    }

    }

  33. @orasio Thanks for your contribution, this is one of the oldest and longest running posts. You would think the issue would be fixed by now, sadly no.

Comments are closed.