Deploy secure Flask applications with Gunicorn, Nginx and Let's Encrypt
Flask is a Python framework for building web applications. With Flask, developers can easily define routing, process HTTP requests and responses, and render dynamic content using Jinja2 templates. It also supports extensions that allow developers to integrate features such as database access, form processing, and user authentication.
This article will explain how to use Gunicorn to deploy Flask applications and implement CSRF protection and content security policies (CSP). We will also set up a reverse proxy using Nginx and apply for a free SSL certificate through Let's Encrypt to implement HTTPS.
Deploy on Vultr-optimized cloud instance
Add demo application code file
sudo apt install python3-venv
python3 -m venv myenv
source myenv/bin/activate
Add demo application code file
git clone https://github.com/mayankdebnath/flask-todo-demo.git
cd flask-todo-demo/sample/
pip install flask gunicorn
ufw allow 5000
Cross-site Request Forgery (CSRF) is a vulnerability that allows an attacker to make unauthorized requests to different websites trusted by the user using a logged-in session on a trusted website. WTForms is a Flask extension that integrates CSRF protection by default to prevent CSRF attacks.
Content Security Policy (CSP) is an additional layer of security for web applications that protect them from malicious attacks. CSP indicates which resources the browser allows to load on a specific web page. Typically, the website administrator configures the CSP by adding special headers to the web page's server response, and the browser then receives the CSP header and understands which resources are allowed to load. Talisman is a Flask extension that simplifies the process of adding CSP to Flask applications.
pip install flask-wtf talisman
nano app.py
from talisman import Talisman talisman = Talisman( app, content_security_policy={ 'default-src': ['\'self\''], 'script-src': ['\'self\'', '\'unsafe-inline\'', 'https://code.jquery.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css', 'https://todoapp5.ddns.net/static/styles.css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css'], }, force_https=True, session_cookie_secure=True, frame_options='DENY', )
from flask_wtf.csrf import CSRFProtect app.config['SECRET_KEY'] = 'your_secret_key_here' csrf = CSRFProtect(app) csrf._csrf_request_token_key = 'X-CSRFToken'
Save and close the file.
cd templates
nano index.html
var csrfToken = $('input[name="csrf_token"]').val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrfToken); } } });
Save and close the file.
8. Exit the templates directory: cd ..
Configure Nginx as reverse proxy
Nginx acts as a reverse proxy between the web server and the client. It boots incoming requests based on your request configuration settings. In this section, we will configure the application for reverse proxying for efficient request processing and load balancing. We will also apply for a free SSL certificate from Let's Encrypt to implement HTTPS, thereby protecting the communication between users and web servers.
ns1.vultr.com
and ns2.vultr.com
. sudo apt install nginx
sudo nano /etc/nginx/sites-available/app.conf
server { listen 80; listen [::]:80; server_name <your_domain>; location / { proxy_pass http://127.0.0.1:5000/; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
sudo ln -s /etc/nginx/sites-available/app.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
sudo ufw allow 80/tcp && sudo ufw allow 443/tcp
sudo snap install --classic certbot
sudo certbot --nginx -d example.com -d www.example.com
(Replace example.com with your domain name) gunicorn -b 0.0.0.0:5000 app:app
https://<your_domain></your_domain>
. Do more with Python app on Vultr
Conclusion
This article explores how to deploy Flask applications using Nginx reverse proxy and Gunicorn, and implement CSRF protection and CSP. We also protect the security of our applications by adding SSL certificates and enabling HTTPS access.
This article is sponsored by Vultr. Vultr is the world's largest private cloud computing platform. Vultr is loved by developers and has provided flexible and scalable global cloud computing, cloud GPU, bare metal and cloud storage solutions to more than 1.5 million customers in 185 countries. Learn more about Vultr
The above is the detailed content of How to Deploy Flask Applications on Vultr. For more information, please follow other related articles on the PHP Chinese website!