How to connect to Mautic API from Javascript with Basic Auth


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 = '';
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) {

The call works perfectly with Postman and Curl

curl --location --request GET '' \
--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 '' \
--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

I totally agree with adiux.

Its a feature from the browser that helps us from malicious actors.

CORS is very helpful security feature that make sure that the request is coming from the verified server and not other unverified servers.

You can add your server name or ip to the mautic configuration and this way, you can make sure that only you can access the servers.

You are using JavaScript fetch() so, you can add either authorization headers or change the setting in the mautic api configuration and add your domain there.

Best Regards,