Can’t set Authorization header for Flask CORS request

When making a cross-site request to an API application such as a Flask application, often there are a few roadblocks. Once you have set up Flask CORS you may believe everything is ready to go with a global configuration like this:

from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"

Then you try to add a HTTP header to all of your JavaScript requests like this:

XMLHttpRequest.prototype.origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
this.origOpen.apply(this, arguments);
this.setRequestHeader('Authorization' , 'Bearer ' + getCookie('mytoken'));
};

But checking the networking console in the browser we see that the headers for all the HTTP requests are now set to:

Access-Control-Request-Headers:authorization

That is not exactly what we want so how do we get Flask CORS to permit the header to be sent by the browser?

The answer is you must add a keyword argument to explicitly allow this header for CORS requests like this:

flask_cors.CORS(app, expose_headers='Authorization')

Now the OPTIONS request has the correct response and the Authorization header will be passed in the subsequent requests.