Crossdomain crossite Ajax calls within a htaccess protected environment

Recently I had the challenge to implement crossdomain crossite Ajax calls within a htaccess protected environment (a crossover between Magento and Contao => both PHP-applications).
But when the one application tried to call the other one via Ajax, I got the following error message in my developer  console in Chrome and Firefox and the call didn’t took place:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at CORS header 'Access-Control-Allow-Origin' does not match '*').

The Problem was, that I had this in my htaccess file of the respective target application, that should receive the Ajax call:

<IfModule mod_headers.c>
  <FilesMatch "\.(html|php|ttf|ttc|otf|eot|woff2?|font\.css)$">
    Header add Access-Control-Allow-Origin *
    Header set Access-Control-Allow-Credentials true

The reason was, that you have to determine a specific domain as Access-Control-Allow-Origin when using Access-Control-Allow-Credentials.

So changing the htaccess as shown below, brought me the expected results:

<IfModule mod_headers.c>
  <FilesMatch "\.(html|php|ttf|ttc|otf|eot|woff2?|font\.css)$">
    SetEnvIf Origin "http(s)?://" AccessControlAllowOrigin=$0
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    Header set Access-Control-Allow-Credentials true

How to test CORS headers :

You can easily test the delivery of the mentioned headers by shell

curl -s --head \
 -X GET \
 -H "Access-Control-Request-Method: GET" \
 -H "Origin:" \
 -H 'Cache-Control: no-cache' \

The -s in combination with –head results in an output, that only contains the response headers.

With -H “Origin:”, we simulate a request from a server with the domains

As a result you should get something like that:

HTTP/2 200 
server: nginx/1.15.5
date: Thu, 08 Nov 2018 12:37:41 GMT
content-type: application/font-sfnt
content-length: 41724
last-modified: Thu, 08 Nov 2018 08:09:39 GMT
x-frame-options: SAMEORIGIN
access-control-allow-headers: origin, x-requested-with, content-type
access-control-allow-methods: PUT, GET, POST, DELETE, OPTIONS
access-control-allow-credentials: true
pragma: no-cache
expires: -1
cache-control: no-store, no-cache, must-revalidate, max-age=0
accept-ranges: bytes
strict-transport-security: max-age=0

As you can see from the access-control-allow-* headers, the htaccess change where successful.

The CORS errors in the browser should disappear.

Leave a Reply

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.