简体   繁体   English

使用PowerShell失败将Azure AD帐户添加为SQL登录名

[英]Adding Azure AD account as SQL login with PowerShell failing

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. 我们正在尝试自动将Azure AD组作为SQL登录名添加到在Azure SQL实例上运行的特定数据库。 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. 当使用SSMS登录到SQL实例并运行命令CREATE USER [<aad_group_to_add>] FROM EXTERNAL PROVIDER它不会执行任何问题,并且不会添加任何帐户。

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 当运行上面的脚本时,我们收到错误Exception calling "ExecuteScalar" with "0" argument(s): "Principal '<aad_group_to_add>' could not be found at this time

We had a similar issue and found that we had to use a AAD username and password for adding groups in a similar fashion. 我们遇到了类似的问题,发现我们必须使用AAD用户名和密码以类似的方式添加组。 I tried everything possible using similar code to yours and settled on this powershell as part of our CI/CD Pipeline: 我使用与您类似的代码尝试了所有可能的方法,并在此Powershell上建立了CI / CD管道:

 $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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM