How to Connect Azure SQL Database from Container App Using Active Directory MSI?

0
8
Asked By CuriousCoder99 On

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.

3 Answers

Answered By HelpfulTechie88 On

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.

CuriousCoder99 -

Yes, I did assign the proper access.

Answered By SQLNinja42 On

Instead of using 'Database=', try 'Initial Catalog='. It’s worth a shot!

TechSavvyDude -

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).

Answered By DBGuru101 On

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!

CuriousCoder99 -

I'll definitely take a look, thanks for the suggestion!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.