29

I want to force Django to use SSL to connect to my postgres database.

This question indicates that I need to pass sslmode='require' to the psycopg2 connect call. How do I add this to Django's database paremeters?

Zags
  • 37,389
  • 14
  • 105
  • 140

4 Answers4

60

Add 'OPTIONS': {'sslmode': 'require'}, to your database config. For example:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': "db_name",
        'USER': "db_username",
        'PASSWORD': "db_password",
        'HOST': "db_host",
        'OPTIONS': {'sslmode': 'require'},
    },
}

As jklingen92 points out, if you are using a database URL, such as through django-environ, add ?sslmode=require to the end of your database URL. For example:

postgres://<DB_USERNAME>:<DB_PASSWORD>@<DB_HOST>:<PORT>/<DB_NAME>?sslmode=require
Zags
  • 37,389
  • 14
  • 105
  • 140
  • 2
    Are you not supposed to pass a certificat ? – Florent Sep 11 '22 at 17:06
  • 1
    @Florent The database client doesn't need to specify a certificate unless you're using the optional clientcert authentication options. How to do that in Django is a [separate question](https://stackoverflow.com/q/35869001/2800876) – Zags Sep 11 '22 at 21:24
9

If you're configuring a database URL, you can pass options as query parameters:

DATABASE_URL=postgres://USER:PASSWORD@HOST:PORT/NAME?sslmode=require

This works with both Django Configurations and with Django Environ. Django Configurations is built off of dj_database_url, so you can also pass ssl_require=True as @frmdstryr said:

DATABASES = values.DatabaseURLValue(environ_required=True, ssl_require=True)
jklingen92
  • 91
  • 1
  • 3
  • 2
    where to specify the certificate ? – Sandeep Balagopal Mar 29 '21 at 08:25
  • 3
    @SandeepBalagopal You can specify paths to SSL certificate by adding the following to OPTIONS (along the aforementioned sslmode attribute): { 'sslmode': 'require', 'sslcert': '/path/to/file', 'sslkey': '/path/to/file', 'sslrootcert': '/path/to/file'} – Oscar Chen Jun 23 '21 at 05:53
4

If you're using dj_database_url you can pass ssl_require=True which sets the option for you.

import dj_database_url
DATABASES['default'] = dj_database_url.config(ssl_require=True)
frmdstryr
  • 20,142
  • 3
  • 38
  • 32
0

Edit the settings.py file like this:

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # },
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'HOST': 'server-ip',
        'PORT': '5432',
        'NAME': 'database-name',
        'USER': 'username',
        'PASSWORD': 'password',
        'OPTIONS': {
            'sslmode': 'require',
            'sslcert': '/path/to/file',
            'sslkey': '/path/to/file',
            'sslrootcert': '/path/to/file',
        },
    },
}

references visit here

Sumit Kumar
  • 678
  • 4
  • 19