Django security best practices - protecting against common web security vulnerabilities | Daoman PythonAI
#django security best practices - protecting against common web security vulnerabilities
📂 Stage: Part 3 - Advanced Topics 🎯 Difficulty Level: Advanced ⏰ Estimated study time: 3-4 hours 🎒 Prerequisite knowledge: 用户认证系统
Table of contents
Security Overview
Web security is a red line that cannot be touched. Fortunately, Django provides powerful built-in protection, but the premise is that we must configure and use it correctly. This section will help you quickly understand the types of attacks that require the most attention and how Django responds to them.
OWASP Top 5 most related to django
- Injection attack: django ORM prevents SQL injection, template automatic escaping prevents XSS
- Broken Access Control: Control access through decorators and permissions system
- Authentication failed: Built-in authentication middleware and password validator protect you
- Security Configuration Error: Built-in
check --deployFind configuration issues with one click - CSRF: Native CSRF middleware directly prevents cross-site request forgery
Core Security Principles
- Minimum permissions: Only give users and processes the most necessary permissions to avoid using super users at will.
- Input whitelist, output fully escaped: Do not use fuzzy filtering instead of whitelist, all data output to the page must be escaped
- Defense in Depth: Layers of defense, even if one layer is breached, there is still protection behind it
- Do not expose sensitive information: It is prohibited to disclose sensitive data such as keys and paths in error pages and logs.
XSS protection
Cross-site scripting (XSS) is one of the most common web attacks. Simply put, the attacker injects malicious scripts into the page, and the scripts are executed when other users access the page, thereby stealing information or impersonating identities.
1. Template automatic escaping - the first line of defense
The django template engine will escape all HTML special characters by default.<become<, so the script will not be executed. The only thing we have to do is not to disable this protection.
Feel free to use|safeThe filter is opening the door to thieves:
Keep auto-escaping, or explicitly useescapeFilter to make the output safe:
2. How to deal with rich text? use bleach
Some scenarios do need to receive rich text input by users. For example, comments can contain bold fonts, line breaks, etc. You can’t simply let go at this timesafe, instead you should use a specialized cleaning library, such asbleach。
Install bleach:
Create a custom template filter to only allow safe tags and attributes:
When used in a template, just load the filter and call it:
3. Content Security Policy (CSP)
CSP is an additional line of defense executed by the browser. It tells the browser through HTTP response headers: which sources of resources can be loaded and which scripts can be executed. Django has some built-in support.
The most basic configuration is to enableSecurityMiddlewareAnd turn on several security headers:
A more complete CSP policy can be configured through custom middleware or at the reverse proxy (such as Nginx) layer, so that each resource type can be finely controlled.
CSRF protection
Cross-site request forgery (CSRF) uses the user's logged-in identity to induce the browser to issue malicious requests without the user's knowledge. Django's native CSRF middleware can prevent most situations.
1. Don’t touch the middleware
make suredjango.middleware.csrf.CsrfViewMiddlewareexistMIDDLEWARE, and in the correct order. It is enabled by default, so do not remove it.
2. Put the CSRF token in the form
All forms submitted through POST requests must include{% csrf_token %}:
3. Don’t forget the token when making AJAX requests
When using Axios on the front end, you can automatically bring the CSRF token. First get it from the cookie, and then set it in the request header:
4. Key settings reinforcement
The production environment must be configured tightly:
SQL injection protection
SQL injection controls the database by splicing malicious SQL statements, which may lead to data leakage or even server control. Django ORM is the cornerstone of preventing SQL injection.
1. Never splice SQL
The following operation is to create vulnerabilities yourself: :::danger Never do this
:::
2. Correct use of ORM and parameterization
All queries should be done via an ORM or parameterized native SQL: ::: tip safe usage
:::
These writing methods can ensure that user input is treated as data instead of being interpreted as SQL code, preventing injection from the source.
Other core security protection
1. Clickjacking Protection
A clickjacking attack hides your page in a transparent iframe to induce users to click. django has built-inXFrameOptionsMiddleware, the appropriate response header is set by default.
The policy can be adjusted through configuration:
2. File upload security
File upload is a high-risk operation. To make the upload safe, it must be verified from three dimensions:
- Extension whitelist
- MIME type checking
- File content integrity verification (especially pictures)
The following is an example implemented using django forms, usingpython-magicandPillow:
3. Password security
Password storage and verification can never be sloppy. Django provides a complete password validator, which must be enabled and enhanced in the production environment:
Production environment security configuration
1. Sensitive information is managed using environment variables
Sensitive data (keys, database passwords) should never be hardcoded in the code. Recommendedpython-decouplefrom.envFile reading:
Install first:
create.envfile (remember to add to.gitignore):
existsettings.pyLoad in:
2. One-click deployment check
Django has a built-in check command that can detect many common deployment security issues:
After running, follow the prompts to correct any problems, especiallySECRET_KEYNot set orDEBUGStill enable such high-risk items.
Security Testing and Tools
1. Write basic security test cases
Write security requirements as automated tests so that every change can be automatically verified:
2. Commonly used security scanning tools
-
Bandit: Static analysis of security issues in Python code
-
Safety: Check for known vulnerabilities in project dependencies
Running these tools regularly can help you plug known vulnerabilities in a timely manner.
Summary of this chapter
- Django has blocked most web attacks for you, but you must configure and use it correctly
- There are only two core concepts: use a whitelist for input and escape all output
- Never splice SQL, stick to ORM or parameterized queries
- The production environment must be shut down
DEBUG, force the use of HTTPS, and enable various security headers - Make good use of automation tools:
check --deploy, Bandit, Safety, regular scanning
Security is not a one-time configuration but an ongoing engineering habit.
Next step to learn
- 性能优化 — pursue speed without compromising safety
- 部署最佳实践 — Implement security configuration into the production environment
🔗 Recommended related tutorials
🏷️ Core Tags:django安全 XSS防护 CSRF防护 SQL注入 生产环境配置

