Skip to content

Instantly share code, notes, and snippets.

@niktho
Created September 21, 2020 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niktho/7b2f4080f28f275ba1a58ce36b335ca6 to your computer and use it in GitHub Desktop.
Save niktho/7b2f4080f28f275ba1a58ce36b335ca6 to your computer and use it in GitHub Desktop.
connect-azure-sql-with-msal-token.ps1
$token = Get-MsalToken -ClientId '<your client id>' -ClientSecret (ConvertTo-SecureString '<your client secret>' -AsPlainText -Force) -Scopes 'https://database.windows.net/.default' -TenantId '<your tenant id>'
$sqlConnection = New-Object System.Data.SqlClient.SQLConnection
$sqlConnection.ConnectionString = "Data Source={0}.database.windows.net;Initial Catalog={1};Connect Timeout=30" -f "myAzureSqlServer", "myAzureSqlDatabase"
$sqlConnection.AccessToken = $token.AccessToken
$sqlConnection.Open()
$command = $sqlConnection.CreateCommand()
$command.CommandText = 'DROP USER IF EXISTS [myUser]; CREATE USER [myUser] FOR EXTERNAL PROVIDER; GRANT CONNECT, SELECT TO [myUser]'
$command.ExecuteNonQuery()
$sqlConnection.Close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment