Flask, Vue & CORS: supports_credentials=True

Photo by Negative Space Pexels

In a web app I am building for work, I came across a situation where I needed to implement CORS. CORS stands for “cross origin resource sharing”.

Please note this post assumes you have some experience with CORS and CORS security. It’s risks involved and benefits as well. Therefore, I am not diving into pros and cons of all the different use cases. I am using Flask, blueprints within my flask app, and Vue.js in the codebase I reference.

The official CORS definition from Wikipedia:

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served

Why did I need to implement CORS? Well, I needed to pass data from server side routes in Flask to front end views in Vue.js. Therefore, I implemented supports_credentials=True. Supporting credentials is what this post is about! Read on to see how to implement using blueprints in Flask.

When I have a route in flask protected with a decorator of @login_required, or perhaps a “check_admin” function checking to see if the user is an admin all being served from port 5000, my vue components will not load data without some extra help from CORS. Why? Vue.js is served on port 8080 in development on my localhost.

CORS is needed when dealing with different domains (ports), outside of the initial domain making the http request, as the definition above explains. So, let’s revisit the definition of CORS for a moment, or parts of it at least. The definition mentions “restricted resources”. What does it mean by a “restricted resource”?

An example in flask would be the @login_required decorator. This decorator makes certain routes restricted within the application. Only a user that is logged in may view the html template (restricted resource).

Documentation is a necessity and super important when developing your own applications. The API docs for flask-cors can be found here, followed by a excerpt from the docs as well.

By default, Flask-CORS does not allow cookies to be submitted across sites, since it has potential security implications. If you wish to enable cross-site cookies, you may wish to add some sort of CSRF protection to keep you and your users safe.

To allow cookies or authenticated requests to be made cross origins, simply set the supports_credentials option to True. E.g.

And it is that simple. By default, Flask-CORS will set supports_credentials=False. So, set it to true. Code below.

Very quick post, but I hope this saves people some time all the while, giving a refresher on CORS, where to find the API docs for Flask-CORS and how to override a default setting if you are dealing with authentication and restricted resources in your flask app.

Happy coding!

I am an obsessive autodidact, I love coffee, early mornings, guitar, camping, traveling with my wife and of course…software development!