Adding Azure AD account as SQL login with PowerShell failing

会有一股神秘感。 提交于 2019-12-11 08:04:18

问题


We are trying to automate the addition of an Azure AD group as a SQL login to a specific database running on an Azure SQL instance. When logging into the SQL instance with SSMS and running the command CREATE USER [<aad_group_to_add>] FROM EXTERNAL PROVIDER it executes with no issues and adds the account with no issues.

Script we are using:

Function Get-AADToken {
  [CmdletBinding()]
  [OutputType([string])]
  PARAM (
      [String]$TenantID,
      [string]$ServicePrincipalId,
      [securestring]$ServicePrincipalPwd
  )
  Try {
      # Set Resource URI to Azure Database
      $resourceAppIdURI = 'https://database.usgovcloudapi.net/'

      # Set Authority to Azure AD Tenant
      $authority = 'https://login.microsoftonline.us/' + $TenantID
      $ClientCred = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential]::new($ServicePrincipalId, $ServicePrincipalPwd)
      $authContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($authority)
      $authResult = $authContext.AcquireTokenAsync($resourceAppIdURI, $ClientCred)
      $Token = $authResult.Result.AccessToken
  }
  Catch {
      Throw $_
      $ErrorMessage = 'Failed to aquire Azure AD token.'
      Write-Error -Message 'Failed to aquire Azure AD token'
  }
  $Token
}

# Variables
$tenantId = '<tenant_id>'
$subscription_Id = '<subscription_id>'
$kvName = "mykv"
$kvSecret = "mysppw"
$spDisplayName = "mysp"
$environmentName = "AzureUsGovernment"

# Login to Azure Resource Management portal
Write-Host "Checking context...";
$context = Get-AzureRmContext
if($null -ne $context){
  if(!(($context.Subscription.TenantId -match $tenant_Id) -and ($context.Subscription.Id -match $subscription_Id))){
    do{
      Remove-AzureRmAccount -ErrorAction SilentlyContinue | Out-Null
      $context = Get-AzureRmContext
      }
    until($null -ne $context)
    Login-AzureRmAccount -EnvironmentName $environmentName -TenantId $tenantId -Subscription $subscription_Id
    }
  }
else{
  Login-AzureRmAccount -EnvironmentName $environmentName -TenantId $tenantId -Subscription $subscription_Id
  }

# Connect to db using specific SQL SP Account "oca-inl-sql-sp1"
$ServicePrincipalId = (Get-AzureRmADServicePrincipal -DisplayName 
$spDisplayName).ApplicationId.Guid
$sql_sp_secret = (Get-AzureKeyVaultSecret -VaultName $kvName -Name 
$kvSecret).SecretValueText
$SecureStringPassword = ConvertTo-SecureString -AsPlainText $sql_sp_secret -Force

# Run the Function to get the AD Token for the sql sp
Get-AADToken -TenantID $TenantID -ServicePrincipalId $ServicePrincipalId - ServicePrincipalPwd $SecureStringPassword -OutVariable SPNToken

# Create connection to sql server
Write-Verbose "Create SQL connectionstring"
$conn = New-Object System.Data.SqlClient.SQLConnection
$SQLServerName = "mysqlsrv"
$DatabaseName = "mydb"
$conn.ConnectionString = "Data 
Source=$SQLServerName.database.usgovcloudapi.net;Initial Catalog=$DatabaseName;Connect Timeout=30"
$conn.AccessToken = $($SPNToken)
$conn

# Create the T-SQL Querys to be executing inside of the sql connection
Write-Verbose "Connect to database and execute SQL script"
$conn.Open()

$query = "CREATE USER [<aad_group_to_add>] FROM EXTERNAL PROVIDER"

# Execute the queries using the connection created previously
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $conn)     
$Result = $command.ExecuteScalar()
$Result
$conn.Close() 

When running the script above, we get the error Exception calling "ExecuteScalar" with "0" argument(s): "Principal '<aad_group_to_add>' could not be found at this time


回答1:


We had a similar issue and found that we had to use a AAD username and password for adding groups in a similar fashion. I tried everything possible using similar code to yours and settled on this powershell as part of our CI/CD Pipeline:

 $query ='
  CREATE USER [GROUPTOADD] FROM EXTERNAL PROVIDER
  ALTER ROLE db_datawriter ADD MEMBER [GROUPTOADD]
  ALTER ROLE db_datareader ADD MEMBER [GROUPTOADD]  
  GRANT CONNECT TO [GROUPTOADD]
  GRANT EXECUTE TO [GROUPTOADD]
'

  $con = "Data Source=$(DatabaseServer);Initial Catalog=$(DatabaseName);User ID=$(ADDatabaseUser);Password='$(ADDbPwd)';Connect Timeout=30;Encrypt=False;Authentication='Active Directory Password'"
Invoke-Sqlcmd -Query $query -ConnectionString $con


来源:https://stackoverflow.com/questions/54082981/adding-azure-ad-account-as-sql-login-with-powershell-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!