0
0
Djangoframework~5 mins

HTTPS and secure cookies in Django

Choose your learning style9 modes available
Introduction

HTTPS keeps data safe by encrypting it between your website and visitors. Secure cookies help protect user information by only sending cookies over HTTPS.

When you want to protect user passwords and personal data on your website.
When you need to keep login sessions safe from hackers.
When handling sensitive information like payment details.
When you want to improve user trust by showing a secure site.
When complying with privacy laws that require data protection.
Syntax
Django
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
Set SECURE_SSL_REDIRECT to force all traffic to HTTPS.
Use SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to make cookies send only over HTTPS.
Examples
This setting makes Django redirect all HTTP requests to HTTPS automatically.
Django
SECURE_SSL_REDIRECT = True
This ensures the session cookie is only sent over HTTPS, protecting login sessions.
Django
SESSION_COOKIE_SECURE = True
This makes the CSRF cookie secure, preventing it from being sent over insecure connections.
Django
CSRF_COOKIE_SECURE = True
Sample Program

This example shows the key settings in settings.py to enable HTTPS redirection and secure cookies. The simple view returns a welcome message. When deployed with HTTPS, cookies will only be sent securely.

Django
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

# settings.py snippet
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

# views.py snippet
@csrf_exempt
def home(request):
    return HttpResponse("Welcome to the secure site!")
OutputSuccess
Important Notes

Remember to have a valid SSL certificate installed on your server for HTTPS to work.

Secure cookies won't be sent over HTTP, so test your site using HTTPS URLs.

Using HTTPS also improves SEO and user trust.

Summary

HTTPS encrypts data between users and your site.

Secure cookies protect sensitive session and CSRF data.

Enable SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, and CSRF_COOKIE_SECURE in Django settings.