Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mailgun API: Request header field Authorization is not allowed by Access-Control-Allow-Headers

How do I set up my .htaccess on my AngularJS application to prevent the following error message:

Failed to load https://api.mailgun.net/v3/example.com/messages: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Here is my .htaccess file:

<IfModule mod_headers.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Content-Type, Authorization"
Header add Access-Control-Allow-Methods "GET, POST"
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ index.html
</IfModule>

I am getting the error message on my website here, whenever the user tries to submit the contact form.

This is my code for the process:

function send(apiUrl, from, to, subject, body, apiKey) {
  var url = apiUrl;
  var dataJSON = {
    from: from,
    to: to,
    subject: subject,
    text: body,
    multipart: true
  };

  var req = {
    method: 'POST',
    url: url,
    headers: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + $base64.encode('api:'+apiKey)
    },
    transformRequest: function (obj) {
      var str = [];
      for (var p in obj) {
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
      }
      return str.join('&');
    },
    data: dataJSON
  };

  $http(req).then(function (data) {
    if(data.data) {
      if(data.data.message === 'Queued. Thank you.') {
        $window.alert('Sent. Thank you.');
      }
      else {
        $window.alert(data.data.message);
      }
    }
    else {
      $window.alert('An error has occured. Please try again.');
    }
  }, function (data) {
    if(data.data) {
      if(data.data.message === 'Queued. Thank you.') {
        $window.alert('Sent. Thank you.');
      }
      else {
        $window.alert(data.data.message);
      }        }
    else {
      $window.alert('An error has occured. Please try again.');
    }
  });
}
like image 213
methuselah Avatar asked Dec 14 '22 17:12

methuselah


1 Answers

You can’t make authenticated requests to the Mailgun API from frontend JavaScript code running in a browser. The Mailgun API intentionally doesn’t support that, per their own documentation:

NOTE: If used in the browser, a proxy is required to communicate with the Mailgun api due to cors limitations. Also, do not publish your private api key in frontend code.

Specifically, for requests from frontend JavaScript code running in browsers, the Mailgun API doesn’t allow the Authorization request header. You can verify that with curl or such:

$ curl -X OPTIONS -H "Origin: https://marquesslondon.com" \
       -i https://api.mailgun.net/v3/marquesslondon.com/messages

HTTP/1.1 200 OK
Access-Control-Allow-Headers: Content-Type, x-requested-with
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 600
Allow: POST, OPTIONS

Notice the value of the Access-Control-Allow-Headers response header that endpoint returns doesn’t include Authorization. That means browsers will block your frontend JavaScript code from sending that API endpoint any request that includes the Authorization request header.

As far as your changes to the .htaccess file for the http://marquesslondon.com site, those are unnecessary and irrelevant; it it doesn’t matter what CORS headers you return from that (your) site, because it’s just the site initiating the request — you’re not sending any requests to it cross-origin.

Instead what matters are the CORS headers returned by the site you are actually sending a request to cross-origin, which is https://api.mailgun.net. And as explained above, that site returns a CORS Access-Control-Allow-Headers response header which tells browsers not to allow requests that include the Authorization header — and that’s what results in you seeing the Request header field Authorization is not allowed error message cited in the question.

like image 112
sideshowbarker Avatar answered Apr 27 '23 11:04

sideshowbarker