Django Hardening
Django is one of the most secure web frameworks out there.
Django hardening refers to the process of securing a Django web application by implementing various measures to mitigate potential security risks and vulnerabilities. These measures aim to protect the application and its data from unauthorized access, data breaches, and other security threats.
However, it’s easy to let things slip out, especially when we are in a hurry to see our project up and running in production. Before exposing our website or our API to the world, we need to take care of some extra details to avoid surprises.
Django Settings for Production
In Chapter 5, in the Splitting the Settings File section, we configured our Django project to use different settings for each environment. As of now, we have the following settings:
To prepare the project for production, we create another settings file in decoupled_dj/settings/production.py
, which will hold all the production-related settings. What should go in this file? Some of the most important settings for production in Django are:
Authentication and Cookies in Django
decoupled_dj/settings/production.py
- Securing Authentication Cookies
With CSRF_COOKIE_SECURE
and SESSION_COOKIE_SECURE
set to True, we ensure that session authentication related cookies are transmitted only over HTTPS.
Randomize the Admin URL
The built-in
admin panel is probably one of the most beloved Django features.
However, the URL for this panel, which by default is admin/
, can be targeted by automated brute force attacks when the website is exposed online. To mitigate the issue, we can introduce a bit of randomness in the URL, by changing it to something not easily guessable.
from django.urls import path, include
from django.contrib import admin
from django.conf import settings
urlpatterns = [
path("billing/", include("billing.urls", namespace="billing")),
]
if settings.DEBUG:
urlpatterns = [
path("admin/", admin.site.urls),
] + urlpatterns
if not settings.DEBUG:
urlpatterns = [
path("77randomAdmin@33/", admin.site.urls),
] + urlpatterns
This code tells Django to change the admin URL from admin/
to 77randomAdmin@33/
when DEBUG is False. With this little change, we add a bit more protection to the admin panel. Let’s now see what we can do to improve the security of our REST API.