Django's CSRF token changes on every single form render. The one in the HTML is never identical to the one in the cookie. That's not a bug, it's the whole point. Here's what actually happens: 1. Django stores a 32-character random secret in the CSRF cookie. That secret never changes across the session. 2. What goes into the form is a masked token. It is a fresh 32-character salt concatenated with the XOR of that salt and the secret. 64 characters total, different every render. 3. On every unsafe request (POST, PUT, PATCH, DELETE), CsrfViewMiddleware.process_view() intercepts. It extracts the salt from the submitted token, XORs back to recover the embedded secret, then compares that to the cookie secret. 4. The tokens never match directly. The secrets do. This masking exists to defeat BREACH. It is a compression-based attack where seeing the same ciphertext repeatedly across responses leaks the underlying secret over time. The trap: - setting CSRF_COOKIE_HTTPONLY = True makes the cookie unreadable by JavaScript. - SPAs that read the token via document.cookie and inject it as X-CSRFToken silently break. Every POST returns 403. The CSRF token is a cryptographic proof that the sender could read a cookie. The XOR masking is what every tutorial skips and what actually makes that proof hold. What's the most confusing CSRF failure that turned out to be a config issue rather than a code bug? #Python #Django #BackendDevelopment #WebSecurity
Django CSRF Token Security Explained
More Relevant Posts
-
I'm currently building a production-ready Calendly clone using Django REST Framework — Day 15 of a 12-week build. Today I implemented JWT authentication with token rotation and blacklisting. Here's one engineering decision that took me time to understand: The refresh token goes in an HttpOnly cookie not localStorage. Why? JavaScript cannot read HttpOnly cookies. That means even if someone injects malicious script into the page (XSS attack), they cannot steal the refresh token. localStorage is accessible to all JavaScript on the page — one vulnerability exposes every user's session. The access token (15 min TTL) goes in the response body and is stored in memory. Short TTL means even if it is stolen, the damage window is small. Small decision. Big security implication. Building this publicly on GitHub as I go: https://lnkd.in/e-bfN9BU #Django #DRF #BackendEngineering #Python #JWT
To view or add a comment, sign in
-
Just published a quick guide on implementing Server-Sent Events (SSE) in Django using Django Channels. A simple alternative for one-way updates like notifications and other things. If you're working with Django and want some real time solutions, this might help. Article: https://lnkd.in/gN8VWJtm #Django #Djangochannels #sse #python #pythondjango
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗨𝗻𝗴𝗹𝗮𝗺𝗼𝗿𝗼𝗎𝘀 𝗣𝗮𝗿𝘁𝘀 𝗢𝗳 𝗗𝗷𝗮𝗻𝗴𝗼 You need static files, media files, and environment variables for your Django project. - Static files are CSS, JavaScript, and images that do not change. - Media files are files uploaded by users, like profile pictures or post images. - Environment variables keep sensitive values out of your codebase. To handle static files: - Create a static folder at the project root - Use STATIC_URL, STATICFILES_DIRS, and STATIC_ROOT in settings.py - Run python manage.py collectstatic before deploying For media files: - Use MEDIA_URL and MEDIA_ROOT in settings.py - Add media files to your project's urls.py - Use ImageField in your models and enctype in your HTML forms To keep secrets out of your codebase: - Use environment variables with python-decouple - Create a .env file and add it to .gitignore - Use config to read values from .env in settings.py Before deploying: - Run python manage.py check --deploy to flag security issues - Address every warning before going live Source: https://lnkd.in/gKfEc-Mf
To view or add a comment, sign in
-
A thought-provoking piece for crafters: "GitHub - Distributive-Network/PythonMonkey: A Mozilla SpiderMonkey JavaScript engine embedded into the Python VM, using the Python engine to provide the JS host environment." PythonMonkey embeds Mozilla's SpiderMonkey JavaScript engine directly into the Python runtime, letting developers call JavaScript from Python and Python from JavaScript within the same process — no serialization or IPC required. The project shares memory backing stores between languages for strings, typed arrays, and buffers, making cross-language data transfer extremely fast. Python dicts and lists automatically behave as JS objects and arrays (and vice versa), with full method support through proxy wrappers. It ships with a CommonJS module system, an event loop (supporting setTimeout and Promises as Python awaitables), and standard JS globals like console and XMLHttpRequest. The project reached MVP in September 2024, installs via `pip install pythonmonkey`, and Distributive actively maintains it while welcoming external contributions.
To view or add a comment, sign in
-
Most Django middleware is written with one method. Django actually offers five. Here's what Django does: 1. Django doesn't call middleware as a single function. It calls specific hooks at specific moments in the request lifecycle. 2. Each hook with a different purpose, different data available and different consequences for what gets returned. a. process_request(request): - Fires after the request object is built - before URL resolution. - The view hasn't been identified yet. Return a response here and URL resolution never happens, view never runs. - Use for: blanket request rejection, IP blocking, early authentication checks. b. process_view(request, view_func, view_args, view_kwargs): - Fires after URL resolution - the view function is now known, but not yet called. - Full access to the view function itself and its arguments. Return a response here and view never executes, but process_response still runs on the way out. - Use for: view-specific logic, caching c. process_response(request, response): - Fires after the view returns - always, regardless of what happened upstream. - Must always return a response, returning None here raises an exception. - Use for: modifying headers, injecting content, logging response metadata. d. process_exception(request, exception): - Fires only when the view raises an unhandled exception. - Return a response and exception is handled, process_response runs normally. - Return None and exception propagates to the next middleware's process_exception. Knowing which hook to use is the difference between middleware that works and middleware that works until it doesn't. Have you ever had a middleware silently break something downstream? #Python #Django #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Excited to release djhero — my open-source Python package for Django developers! After building multiple production Django projects, I kept repeating the same patterns: rate limiting, caching, auth guards, JSON validation, CORS, logging... So I packaged them all into one library. 📦 pip install djhero ✅ 24 ready-to-use decorators ✅ Rate limiting (@rate_limit("100/h")) ✅ Per-user caching (@cache_per_user) ✅ Auth & permissions (@auth_required, @staff_required) ✅ JSON validation (@validate_json) ✅ CORS, ETag, pagination, retry & more ✅ 5 built-in signals for monitoring ✅ Django 4.0–5.1 + Python 3.8–3.13 support Instead of installing 5+ separate packages, djhero gives you everything in one place — production-ready, zero hassle. Example: @rate_limit("100/h") @cache_view(ttl=300) @auth_required() @handle_exceptions @json_response def my_api(request): return {"status": "clean & fast"} 🔗 GitHub: github.com/pyaidev/djhero 🔗 PyPI: pypi.org/project/djhero Feedback, stars ⭐ and contributions are very welcome! #Python #Django #OpenSource #WebDevelopment #Backend #DeveloperTools
To view or add a comment, sign in
-
-
Most people building React frontends with Python backends overcomplicate the connection. React and FastAPI is honestly one of the cleanest full-stack combos right now. Here's why it works so well FastAPI gives you automatic docs at /docs the moment you define a route. No extra setup. Your React dev knows exactly what endpoints exist and what they return before you've even written the fetch call. Pydantic schemas on the FastAPI side act as a contract. If the backend returns a User object, you know exactly what fields are coming. Pair that with TypeScript interfaces on the React side and you've eliminated an entire class of runtime bugs. CORS setup is two lines. Async endpoints mean your API doesn't choke when React fires multiple requests simultaneously. Response times stay fast without extra infrastructure. The pattern that works in prod: FastAPI handles all data logic, auth, and business rules React owns the UI state and user interactions entirely They talk only through clean typed API boundaries No shared state nightmares. No tightly coupled mess. If you're coming from a Django or Express background and haven't tried this stack yet, it's worth a weekend project. The developer experience gap is noticeable. What's your go-to Python backend when building React apps? #React #FastAPI #Python #FullStackDevelopment #WebDevelopment
To view or add a comment, sign in
-
Is it worth learning Regex for me? 🤔 Date: 12/4/2026 Today, I take a mini react challenges - Password Strength 💡 In this project real time tracking is lowercase, uppercase, number and symbols used in password filed and based upon increase progress bar. I can make this project using ASCII Code Values and if/else. 😎 But? 🤔 If I do it, then I cannot learn anything new. So, I watched Regex one shot on YouTube. 😊 And learn basic Regex, then I make this project. After make this project, I realized the power of Regex. 😎 GitHub Repo: https://lnkd.in/giWCzFJh #WebDevelopment #Regex #React #Programming #Frontend #JavaScript
To view or add a comment, sign in
-
I built a GUI server you can call from any program with zero GUI dependencies : You know what's genuinely painful? When your program needs to ask the user something. Just one thing. A filename. A number. A confirmation. And suddenly you either have to pull in a full GUI library as a dependency, or you ship a CLI that feels like shit, or you just hardcode it and pray. So I built fxgui. fxgui is a local runtime GUI server. You run it as a background process, and any program - in any language - can talk to it via pure HTTP calls. You ask it to show a window. It shows a window. You ask it to update a progress bar. It updates it. You ask it to prompt the user for a string. It blocks until the user types something and returns the value. No GUI lib linked to your program. No dependencies. No framework to wrestle with. Just HTTP calls. Think about where this becomes actually useful. Your CLI tool needs user input ? No need to pull in Qt for 3 buttons. You have a long loop and you want a progress bar without freezing anything ? Done, from any thread. You're writing a Blender plugin and you want a proper progress window ? Oh yes. That last one. If you've ever tried to show a progress bar from a background operation in Blender's Python API, you know what I'm talking about. Their modal operator system is a nightmare. With fxgui, you just fire an HTTP call and keep running. The API is pure HTTP under the hood, which means you can use it from C++, Python, JavaScript, Rust, Go, whatever. The C++ and Python wrappers are just thin layers on top. If you can make an HTTP request, you can use it. The server is the dependency, not your codebase. That's the whole point. Still in development, but it'll be open source and free once it's out. In the meantime, https://lnkd.in/gZWWQAqQ
To view or add a comment, sign in
-
Every programming language has a superpower, which makes them tailor-made for a particular purpose. And good developers know exactly when to use what. For example: Python → This language can build fast. It's great for MVPs, automation, and AI. JavaScript → Runs everywhere, be they be frontend, backend, or even apps. TypeScript → Adds safety, fewer bugs, and more predictable code. PHP → Still powers a huge part of the web. simple and reliable for many use cases. Go → Built for performance, great for scalable systems and backend services. This proves that no language is “the best”. But every language is powerful in the right hands. The problem isn’t the tool, it’s using the wrong tool for the wrong problem.
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Can I ask what about packages like django-allauth.headless where the token is not HTTPONLY?