Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force SSL for Django Postgres connection

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?

like image 695
Zags Avatar asked Dec 06 '17 20:12

Zags


3 Answers

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
like image 61
Zags Avatar answered Oct 27 '22 19:10

Zags


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)
like image 28
jklingen92 Avatar answered Oct 27 '22 20:10

jklingen92


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)
like image 4
frmdstryr Avatar answered Oct 27 '22 21:10

frmdstryr