Mautic Community Forums

How to connect to Mautic API from Javascript with Basic Auth

Hi

Im trying to connect to my Mautic API from Javascript. I’m getting stuck with a CORS error:
Request header field authorization is not allowed by Access-Control-Allow-Headers

My standard JavaScript API call with fetch:

// using Fetch API
var mauticUrl = 'http://mautic.ddev.site/api/contacts';
var myHeaders = new Headers();
myHeaders.append("Authorization", 'Basic ' + btoa('myuser:mypswd'));

fetch(mauticUrl, {
    credentials: "include",
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json'
    },
    headers: myHeaders
}).then(function (response) {
    return response.json();
}).then(function (json) {
    console.log(json);
});

The call works perfectly with Postman and Curl

curl --location --request GET 'http://mautic.ddev.site/api/contacts/' \
--header 'Authorization: Basic KEY'

Tested on the Mautic ddev setup with Mautic 3.00 beta. And on my production setup 2.16

Is the authorization header missing from Mautic? Something wrong with my header?

Thanks for any help!

Edit 25.5.2020
After some debugging I found part of the solution.

The first problem was that the headers Access-Control-Request-Headers and Origin have to be present in the request otherwise no CORS headers are returned.

An example where CORS headers are returned:

curl -s -I -X  --location --request OPTIONS 'http://mautic.ddev.site/api/contacts/1' \
--header 'Access-Control-Request-Headers: origin, content-type, accept' \
--header 'Origin: http://localhost'

Hint: If you restrict the CORS domains in the Mautic CORS Settings, also make sure the Origin matches the value specified there.

So this solved my intermediate problem “why I’m not getting the CORS headers when I call the API from the console”. But my original problem in the browser still persists.

If I’m correct then the Mautic code only allows me to set these headers:
Origin, X-Requested-With, Content-Type

This brings me to the conclusion that the only way to fix this is by changing the code, or the server config? Is there something that I’m missing?

1 Like