Flask Cors

Posted onby admin
Modified

CORS with create-react-app, Flask, and minikube. In my case, my API server is built using Flask, and I’m using JWT for client authentication using Flask-JWT-Extended. From flask import Flask from flaskcors import CORS app = Flask (name) CORS (app) # This will enable CORS for all routes Important note: if there is an error in your route, let us say you try to print a variable that does not exist, you will get a CORS error related message which, in fact, has nothing to do with CORS.

This vulnerability has been modified since it was last analyzed by the NVD. It is awaiting reanalysis which may result in further changes to the information provided.

Current Description

An issue was discovered in Flask-CORS (aka CORS Middleware for Flask) before 3.0.9. It allows ../ directory traversal to access private resources because resource matching does not ensure that pathnames are in a canonical format.


Analysis Description

An issue was discovered in Flask-CORS (aka CORS Middleware for Flask) before 3.0.9. It allows ../ directory traversal to access private resources because resource matching does not ensure that pathnames are in a canonical format.

Severity

CVSS 3.x Severity and Metrics:
NIST:NVD
Vector:NVD
Vector:HyperlinkResourcehttp://lists.opensuse.org/opensuse-security-announce/2020-09/msg00028.htmlhttp://lists.opensuse.org/opensuse-security-announce/2020-09/msg00032.htmlhttp://lists.opensuse.org/opensuse-security-announce/2020-09/msg00039.htmlhttp://lists.opensuse.org/opensuse-security-announce/2020-09/msg00048.htmlhttps://github.com/corydolphin/flask-cors/releases/tag/3.0.9Third Party Advisoryhttps://www.debian.org/security/2020/dsa-4775

Weakness Enumeration

CWE-IDCWE NameSource
CWE-1188Insecure Default Initialization of ResourceNIST

Known Affected Software Configurations Switch to CPE 2.2

Denotes Vulnerable Software
Are we missing a CPE here? Please let us know.

Change History

6 change records found show changes

2020-02-21T11:06:26Z

Posted by Miguel Grinberg under Python, JavaScript, Flask, Programming, Video.

One of the questions I get asked more often lately is how to create a project that combines a React frontend with a Flask backend. Instead of giving vague answers I decided to write a tutorial about it, including a video in which I go through the steps to create a simple but fully functional React+Flask project.

Requirements

You need to install three packages on your machine:

  • Node.js: The JavaScript runtime that you will use to run your frontend project.
  • Yarn: A package and project manager for Node.js applications.
  • Python: A recent Python 3 interpreter to run the Flask backend on.

Please install these three packages using the instructions for your operating system before continuing with the tutorial.

Creating a Starter React Project

There are several ways to create a combined project with React and Flask. I prefer to start from the frontend because the project structure is much more complex than the backend. For this example I used the create-react-app generator to create a simple React project to start from:

The npx command comes with Node.js. It is a simple project runner that downloads the requested command if it isn't already available and in the system's PATH. The first argument is the command to execute. The second argument is the name of the project to create. When this command completes, you will have a react-flask-app directory with a complete and fully functional simple react project.

Since you will work on this project from now on, you can cd into react-flask-app so that it is your current directory. If you list the directory you should see the top-level structure, which should be more or less like this:

Creating a Flask API Backend

The next step is to create the Flask project. Since I want to have both the frontend and backend combined into a single project, my preference here is to add one more top-level subdirectory where the Flask project will live:

I always create a virtual environment called venv in my project directory, so let's do that now:

Flask cors allow all

Note that the above is for Unix-based operating systems. If you are using Windows, then you will do this instead:

For this simple example I need only two Python packages, the obvious Flask and also python-dotenv:

The Flask project can have any structure that you like, as long as its root is this new api subdirectory. In particular, you can use large and complex structures such as those in my Flask Mega-Tutorial or O'Reilly Flask book, as well as much simpler single file applications. In the spirit of keeping things simple, for this example I'm going to create a small, single file and single endpoint application. Here is my Flask API project, written as a single file called api.py:

This little API responds to the /time URL with a JSON payload such as this:

If you are surprised that you are not seeing a call to the jsonify() function from Flask, you may not be aware that in recent releases of Flask your view function can return a dictionary, which gets automatically JSONified by Flask.

Flask Cors

As you probably know, Flask imports the application from the place indicated by the FLASK_APP environment variable. To avoid having to manually set this variable every time, I'm going to write a .flaskenv file, which Flask automatically imports into the environment on startup if it finds the python-dotenv package installed. Here is my .flaskenv file:

Since I'm going to be setting up development environment, I also added the FLASK_ENV variable, with a setting of development, which enables Flask's debug mode.

At this point this basic Flask project is complete. To make sure that it is working well you can start it:

To stop the Flask server press Ctrl-C.

Flask

Now that the Flask part of this project is complete, let's leave the api subdirectory and go back to the root of the combined project.

React Configuration Changes

The React project created by the create-react-app utility left a package.json file with the project's configuration. There are a couple of changes to make in this file to improve the integration between the React and the Flask sides.

The first change is to set up 'proxy' redirection from React to Flask. You will see in a moment that the React project will run a web server on port 3000, while Flask runs its own server on port 5000. In most deployments, however, the frontend files and the API endpoints are all served from the same domain and port, which makes everything work seamlessly by avoiding cross-origin issues. The React project can be configured to redirect any requests it receives on its port 3000 that it does not understand into another server. This is configured simply by adding a proxy key at the bottom package.json:

When you do this, do not forget to add a comma at the end of the previous line, as without that comma the file would not be a valid JSON file.

The other change I like to make is related to management commands. The React application uses yarn as a command manager. For example, the frontend server is started with the yarn start command. There is also a yarn test and a few more commands.

While this is entirely optional, the commands to manage the Flask app can be integrated with yarn as well. Somewhere in the middle of package.json you will find a scripts key. You can add any custom commands inside it:

Here I've added one new entry called start-api, which I'm going to use to run the Flask server. The value of this key is the command that needs to be executed, which in this case involves changing into the api subdirectory and then running the flask run command.

Note that I have used the virtual environment path for the flask command so that I don't need to have the virtual environment activated. The nice thing about running the command in this way is that in the context of the Flask process all imports will work in the same way as with an activated virtual environment.

The --no-debugger option that I added in the command also deserves a mention. Since this Flask backend is strictly an API server, we will never be serving complete pages, so having the browser-based debugger enabled serves no purpose, as it's just going to mess up the JSON responses that the API returns. You will see stack traces of your errors in the terminal.

Adding the Flask Project to Git

The React starter project includes a git repository, which is actually a nice feature. To make it more friendly to Python there are a couple of things that need to be added to the .gitignore file:

Flask Cors Header

This will prevent the virtual environment and the cache bytecode directories that Python 3 creates from ever getting added to source control. You can add any other things that you need here for your project as well.

CorsFlask cors python

Once your .gitignore is configured you can add all the new and modified files to git and commit the Flask backend:

Running the Combined Project

Okay, now the most exciting part. Let's run the application!

To do this you will need to use two terminal windows. One for the frontend server, and another for the backend. On the first terminal, start the frontend:

This will take a few seconds and then a browser window will open with the example application from React loaded from http://localhost:3000:

When you have the frontend running, switch to your second terminal and start the Flask backend at http://localhost:5000:

Now both the frontend and backend are running. The frontend will redirect any requests it does not recognize to the backend. Both are watching their source code files and will restart when changes are made. I find this setup very convenient, because now I can just concentrate on writing code and the two servers refresh automatically as the code changes.

Invoking a Flask Endpoint from React

To complete this project, I'm going to expand the React application with a call to the /time endpoint that I defined in the Flask side. The main source file for the React application is src/App.js. This is this file after I put my changes:

As soon as you save the src/App.js file with the above changes, the application should update and show the current Unix time:

There are a few small changes here. In the first line I added two new imports, useState and useEffect. I'm going to use the former to add the current time as state within the React application. The latter is used to create a callback that will be invoked when the application renders to the page, which is the time the Flask endpoint needs to be invoked.

In case you are used to writing React applications using classes and components, you should note that you can still do that, but the currently recommended practice is to use a function based approach. JavaScript projects tend to change often, sometimes in drastic ways. You should keep in mind that this isn't the only way to write a React application.

To add state to the application you use the useState() function:

The function returns two values, a getter and a setter for the new state. The getter is a simple variable, while the setter is a function. Using a setter function is necessary because by invoking the setter React is able to trigger updates in the parts of the application that depend on this state. The 0 that I'm passing as an argument to useState() is the initial value for this state variable.

Now that the state variable exists, it can be added to the template portion of the application:

This can be added anywhere in the template, and in fact, if you prefer you can erase the content used by the default React application and replace it with this.

The final part of this example application is to issue a request from the frontend to the backend:

This needs to happen at a specific time when the React application is about to be displayed on the page. The useEffect() function is used to set up a callback function to be invoked when the application needs to prepare itself to render.

Python Flask Cors Allow

The first argument is the callback function. In this function I used fetch() to send the request over to the Flask API. Because of the proxy configuration I don't have to use the port 5000 URL, I can just use /time, which will make the request go to http://localhost:3000/time, before it gets redirected to port 5000. If you decide to not use the proxy feature and send the requests directly to port 5000, you will also need to configure CORS in the Flask server to allow this, since now you will be issuing the request across different origins.

The fetch() function returns a promise, so I set up a completion callback with the then() method. This callback receives the response as res, and then calls the res.json() method to convert the payload to a JavaScript object. This is yet another promise, so I have to chain a second then() with one more callback function. This final callback receives the JSON data from the request, which is an object with a single time attribute. Here I can use the setCurrentTime() setter function to update the currentTime state, which is referenced in the template, so as soon as the state changes the new value will be rendered.

The second argument to useEffect() is optional and can be set to the list of state variables on which this callback depends. In this case I wanted to display the time when the page appears initially and then stay fixed to that, so I'm sending an empty list to eliminate all dependencies. This means that this callback will be invoked on initial rendering and never again. If this argument isn't set, the default is to make this callback dependent on all state variables. This means that when the setCurrentTime() setter is called there will be another call into this function, which will cause the state to change again and keep causing recursive invocations in an endless loop.

Update: I have now written a second part to this tutorial where I show how to deploy this project to a production server.

Conclusion

So that's it, now you know how to create a project that combines React with Flask. As I hinted earlier, this isn't the only way to combine these two frameworks, so I encourage you to experiment with them and find what works best for you.

Do you use a different method? I'd love to know how you think it compares to mine, so let me know below in the comments!

Hello, and thank you for visiting my blog! If you enjoyed this article, please consider supporting my work on this blog on Patreon!

108 comments

  • #1John said 2020-02-22T03:28:56Z

  • #2Hazir said 2020-02-22T07:19:15Z

  • #3Miguel Grinberg said 2020-02-22T11:56:52Z

  • #4Miguel Grinberg said 2020-02-22T12:01:28Z

  • #5Kyle M. said 2020-02-25T02:16:50Z

  • #6Hazir Magron said 2020-02-26T05:34:48Z

  • #7Miguel Grinberg said 2020-02-26T18:05:59Z

  • #8Hazir Magron said 2020-02-27T18:27:04Z

  • #9Miguel Grinberg said 2020-02-28T11:50:22Z

  • #10Yuriy said 2020-02-29T13:14:28Z

  • #11Alex said 2020-03-02T01:27:31Z

  • #12Gyn said 2020-03-02T01:29:46Z

  • #13Miguel Grinberg said 2020-03-02T11:24:38Z

  • #14Miguel Grinberg said 2020-03-02T11:25:37Z

  • #15Akshay said 2020-03-05T18:13:11Z

  • #16mrob said 2020-03-09T17:07:56Z

  • #17Miguel Grinberg said 2020-03-10T11:33:55Z

  • #18Love to see this said 2020-03-14T13:17:43Z

  • #19Harry said 2020-03-18T20:47:27Z

  • #20Shikhar said 2020-03-19T09:58:21Z

  • #21Miguel Grinberg said 2020-03-19T19:36:21Z

  • #22Serve the bundled .js file of react on the flask server [only 1 server] said 2020-03-21T21:13:51Z

  • #23Miguel Grinberg said 2020-03-21T23:55:30Z

  • #24Yahyaa said 2020-03-22T05:01:33Z

  • #25Jonathan Villanueva said 2020-03-22T20:21:06Z

How To Install Flask Cors

Leave a Comment