Connect Django with Azure MS SQL Server DB using managed identity

How can I connect my Azure MS SQL Server Database to Django through managed Identity.

Currently my Django settings.py file looks like this :

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'HPI_SI_DB',
        'HOST': 'abcengine.database.windows.net',
        'USER': 'xyz',
        'PASSWORD': '*******',
        'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server', }
    },
    'DB2': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'HPI_SI_DB',
        'HOST': 'abcdengine.database.windows.net',
        'USER': 'xyz',
        'PASSWORD': '*******',
        'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server', }
    }
}

To configure the application’s database in settings.py. Enter the MySQL database information associated with the Windows Azure Web Site.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'MYSQL-DATABASE-NAME',                     
        'USER': 'MYSQL-SERVER-USER-NAME',                     
        'PASSWORD': 'MYSQL-SERVER-USER-PASSWORD',                  
        'HOST': 'MySQL-SERVER-NAME',                     
        'PORT': '',
    }
}

Next, add your application to your INSTALLED_APPS setting in settings.py.

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',  
    'myblog',
    )

Reference - https://azure.microsoft.com/en-in/blog/using-django-python-and-mysql-on-windows-azure-web-sites-creating-a-blog-application/

From the documentation

ActiveDirectoryMsi

To use managed identity, add Authentication=ActiveDirectoryMsi to extra_params.

DATABASES = {
  "default": {
      "ENGINE": "mssql",
      "NAME": "your_db",
      "HOST": "database.windows.net",
      "PORT": "1433",
      "OPTIONS": {
          "driver": "ODBC Driver 17 for SQL Server",
          "extra_params": "Authentication=ActiveDirectoryMsi",
      },
  },
}

If you want to run unit test then the test database must be manually created and you need to pass in the --keepdb argument.

If you are getting a VIEW ANY COLUMN MASTER KEY DEFINITION permission denied in database error run EXEC sp_addrolemember N'db_owner', N'<Name>', replacing <Name> with the name of the VM in system-assigned managed identity or the name of the managed identity in user-assigned managed identity.

Back to Top