XHR2 file upload to subdomain token mismatch in Laravel5.1/nginx upload module

193 views Asked by At

I am using Laravel5.1 for both domain.com and upload.domain.com, the same script(copy pasted and changed the site url in the config file).

Session domain is set to .domain.com and on upload.domain.com I have added all the CORS headers to upload.domain.com and ajax posts work fine, and using database for the sessions.

I have the following nginx config:

location /upload {

add_header Access-Control-Expose-Headers Accept-Ranges;
add_header Access-Control-Expose-Headers Content-Encoding;
add_header Access-Control-Expose-Headers Content-Length;
add_header Access-Control-Expose-Headers Content-Range;
add_header accept_ranges bytes;

upload_state_store /tmp;
upload_resumable on;
add_header Pragma no-cache;
add_header X-Content-Type-Options nosniff;
#add_header Cache-control "no-story, no-cache, must-revalidate";

# Access control for CORS
{ ....}

add_header X-CSRF-Token $HTTP_X_CSRF_TOKEN;
add_header X-XSRF-TOKEN $HTTP_X_CSRF_TOKEN;
upload_set_form_field "_token" $HTTP_X_CSRF_TOKEN;

client_max_body_size 4096m;
upload_pass /internal_upload;
upload_pass_args on;

upload_store /storage/uploaded 1;
upload_store_access user:r group:r all:r;
upload_set_form_field $upload_field_name.name "$upload_file_name";
upload_set_form_field $upload_field_name.path "$upload_tmp_path";
upload_cleanup 400 404 499 500-505;


}

location /internal_upload {

proxy_pass http://upload.domain.com/fileupload/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

When doing XHR2 requests I pass the token via the header using:

xhr.setRequestHeader("X-CSRF-Token", globalObj._token );
xhr.setRequestHeader("X-XSRF-TOKEN", globalObj._token );

And finally the problem is in the final step when nginx passes the data to the backend application on the subdomain the token mismatch exception is thrown.

I also noticed that domain.com sets a cookie called X-XSRF-TOKEN and uses domain.com as domain name and upload.domain.com sets another X-XSRF-TOKEN token with domain name upload.domain.com. Is this normal because both of the applications set X-XSRF-TOKEN and the values are not equal, and i guess this might be the problem or maybe nginx strips some data and then passes them to the backend?

1

There are 1 answers

0
iNDicator On

For future references, I had to send the cookie which is set in the main domain along with the xhr2 request. This is done by changing the xhr settings to:

xhr.withCredentials = true;