How to Connect Azure SQL Database from Container App Using Active Directory MSI?
Asked by
harpsichord.8
I'm trying to connect to an Azure SQL Database from a Container App and I'm using the 'Authentication=ActiveDirectoryMsi' setting in my connection string. However, I'm encountering a login failure error:
When using pyodbc, I have the following connection string set up:
```python
conn_str = (
"DRIVER={ODBC Driver 18 for SQL Server};"
"Server=,1433;"
"Database=;"
"Encrypt=yes;TrustServerCertificate=no;"
"HostNameInCertificate=*.database.windows.net;"
"Authentication=ActiveDirectoryMsi;"
"Connection Timeout=30;"
)
conn = pyodbc.connect(conn_str)
credential = ManagedIdentityCredential()
token = credential.get_token("https://database.windows.net/.default").token
token_bytes = token.encode("UTF-16-LE")
token_struct = struct.pack("<I", len(token_bytes)) + token_bytes
SQL_COPT_SS_ACCESS_TOKEN = 1256
conn_str = (
"DRIVER={ODBC Driver 18 for SQL Server};"
"SERVER=,1433;"
"DATABASE=;"
"Encrypt=yes;"
"TrustServerCertificate=no;"
"Connection Timeout=30;"
)
conn = pyodbc.connect(conn_str, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct})
```
Both attempts lead to the following error:
Connection failed: ('28000', "[28000] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Login failed for user ''. (18456) (SQLDriverConnect)").
I've already checked:
- My container app exists as EXTERNAL_USER in the database.
- SQL Server allows Azure Services access.
- My container app has system assigned identity enabled.
What could be going wrong? Everything seems set up correctly, yet I am receiving an error.
Answers
If you're not strictly tied to using pyodbc, consider switching to the new Microsoft driver. It simplifies managing Entra ID tokens and works similarly to pyodbc. Check it out here: [Microsoft SQL Driver](https://github.com/microsoft/mssql-python). This should help streamline your connection process!
Reply to this answer
Instead of using 'Database=', try 'Initial Catalog='. Itโs worth a shot!
25g ground cumin: Actually, for ODBC you should stick with 'Database='. You can check here for more details - [ODBC DSN and connection string keywords](https://learn.microsoft.com/en-us/sql/connect/odbc/dsn-connection-string-attribute?view=sql-server-ver17).
Reply to this answer
Make sure you've assigned the proper access for the Managed Service Identity (MSI) on the database itself. Without the right permissions, the connection will fail.
harpsichord.8: Yes, I did assign the proper access.
Reply to this answer
Add your answer
Answers are reviewed before publication.
harpsichord.8: I'll definitely take a look, thanks for the suggestion!