microsoft / go-sqlcmd

The new sqlcmd, CLI for SQL Server and Azure SQL (winget install sqlcmd / sqlcmd create mssql / sqlcmd open ads)
https://learn.microsoft.com/sql/tools/sqlcmd/go-sqlcmd-utility
MIT License
323 stars 56 forks source link

Service Principal that is Azure AD admin cannot connect to database #517

Closed Neutrino-Sunset closed 3 months ago

Neutrino-Sunset commented 3 months ago

I have an Azure SQL server.

I have a service principal that is a member of the security group that is set as the Azure AD admin for the SQL server.

An Azure AD admin for the server should be able to log into any database in the server as database owner.

I can connect to the Azure SQL server using the service principal using this command

sqlcmd -S tcp:sqlsvrname.database.windows.net -U service_principal_id>@<tenant_id -P --authentication-method=ActiveDirectoryServicePrincipal

I now need to create a database user mapped to the Azure AD system assigned managed identity of an Azure Web App.

However I cannot access the database.

The use databasename fails with the error USE statement is not supported to switch between databases. Use a new connection to connect to a different database.

Attempting to connect to the database with the command

sqlcmd -S tcp:sqlsvrname.database.windows.net -d databasename -U service_principal_id>@<tenant_id -P --authentication-method=ActiveDirectoryServicePrincipal

Fails with the error mssql: login error: Login failed for user '<token-identified principal>'

How do I connect to a database using an Azure AD admin service principal?

sqlcmd --version                                                                                
sqlcmd: Install/Create/Query SQL Server, Azure SQL, and Tools

Version: v1.6.0
shueybubbles commented 3 months ago

Are you creating the database using TSQL in master from a connection using the service principal account? The rules about which accounts get added to the new database automatically are a bit fuzzy when the Entra Admin account is a group, IIRC.

Can you connect to the database using any other Entra admin login, and inspect the list of logins and role memberships on it?

Neutrino-Sunset commented 3 months ago

It was my mistake. I mis-spelled the name of the database.