Django and Security

Many people have asked me: Is django secure?

Luckily, with django we don’t have to worry about basic security at all. Here is a list of basic security stuff that django supports right out of the box.

  • Cross site scripting (XSS) protection
  • Cross site request forgery (CSRF) protection
  • Full CORS support
  • SQL injection protection
  • Clickjacking protection
  • SSL/HTTPS
  • Host header validation
  • Session security

On top of this we lock down production deployments as follows:

  • Set SECURE_HSTS_SECONDS. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems.
  • SECURE_CONTENT_TYPE_NOSNIFF set to True, so your pages will not be served with an ‘x-content-type-options: nosniff’ header. You should consider enabling this header to prevent the browser from identifying content types incorrectly.
  • SECURE_BROWSER_XSS_FILTER set to True, so your pages will not be served with an ‘x-xss-protection: 1; mode=block’ header. You should consider enabling this header to activate the browser’s XSS filtering and help prevent XSS attacks.
  • SECURE_SSL_REDIRECT set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS.
  • SESSION_COOKIE_SECURE set to True. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions.
  • Set CSRF_COOKIE_SECURE to True. Using a secure-only CSRF cookie makes it more difficult for network traffic sniffers to steal the CSRF token.
  • DEBUG set to False in deployment.
  • X_FRAME_OPTIONS set to ‘DENY’. The default is ‘SAMEORIGIN’, but unless there is a good reason for your site to serve other parts of itself in a frame, you should change it to ‘DENY’.

Additional Security Features

django features a range of third-party open source modules that improve security, for example access logging and application firewalling: https://djangopackages.org/grids/g/security/