Azure Automation Runbook ADAL SQL support - sql-server

I am attempting to use an Azure Automation Runbook to run a query against an Azure SQL database using Azure AD credentials:
$cred = Get-AutomationPSCredential -Name 'SqlAdminUser'
$Username = $cred.UserName
$Password = $cred.GetNetworkCredential().Password
$Server = 'server.database.windows.net'
$Port = 1433
$cxnString = "Server=tcp:$Server,$Port;Database=$Database;Authentication=Active Directory Password;UID=$UserName;PWD=$Password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
$cxn = New-Object System.Data.SqlClient.SqlConnection($cxnString)
$cxn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($query, $cxn)
$cmd.CommandTimeout = 120
$cmd.ExecuteNonQuery()
$cxn.Close()
and I get the following error:
Keyword not supported: 'authentication'.
So it seems like Azure Automation doesn't have the ADAL SQL library installed? Is there any easy way to work around this (and still use an Azure AD account to connect)?
I used this example as a starting point.

You are fetching username and password from $SqlCredential but you stored credentials in $cred variable. These variables need to be same. Also make sure an automation credential object is created in azure automation account with same name as 'SqlAdminUser'

In the end I created hybrid workers which allowed me to install the latest version of the ADAL SQL library, which supports Azure AD authentication.

Related

AAD connect provisioning credentials

How can I find the credentials for this?
Please see image below.
I Tried to reproduce the same in my environment to connect using GMSA
First install ACTIVE DIRECTORY DOMAIN SERVICES and create service account for windows server using the below powershell.
Before executing the powershell script, kindly create one Security name GMSA-Test
PrincipalsAllowedToRetrieveManagedPassword is Security Group Name
Import-module ActiveDirectory
Add-KdsRootKey -EffectiveTime ((get-date).addhours(-10))
New-ADServiceAccount <youraccountname> -DNSHostName ITFarm1.contoso.com -PrincipalsAllowedToRetrieveManagedPassword <GMSA-Test> -KerberosEncryptionType RC4, AES128, AES256 -ServicePrincipalNames http/ITFarm1.contoso.com/contoso.com, http/ITFarm1.contoso.com/contoso, http/ITFarm1/contoso.com, http/ITFarm1/contoso
get-ADServiceAccount GMSAtest
Install ADServiceAccount using powershellon AAD Connect Server
Install-ADServiceAccount -Identity <youraccountname>
successfully created service account after ran the powershell commands.
Configure AAD connect with your Service Account.
Service Account Name: your domain\GMSAtest$
Password: PrincipalsAllowedToRetrieveManagedPassword
Reference: Using Azure AD Connect with a gMSA - The things that are better left unspoken (dirteam.com)

"Assign an Azure AD identity to your server and add Directory Reader permission to your identity" - Error

I am writing a little thing in YAML to assign permissions to a newly built SQL Server.
az account set --subscription $(SubscriptionId)
Install-Module -Name SqlServer -Force
$sqlCmd = "CREATE LOGIN [Users-PreProd2] FROM EXTERNAL PROVIDER"
Write-Host $env:tenantId
$request = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$env:tenantId/oauth2/token" -Body #{ resource="https://database.windows.net/"; grant_type="client_credentials"; client_id=$env:servicePrincipalId; client_secret=$env:servicePrincipalKey } -ContentType "application/x-www-form-urlencoded"
$access_token = $request.access_token
Invoke-Sqlcmd -ServerInstance database.windows.net -AccessToken $access_token -query $sqlCmd
I have a group called User-PreProd which i need adding as a 'CREATE LOGIN' in SQL. I have added the Service Prinicipal in the Azure AD Admin group. I can get the token fine and when i assign the token to the invoke-Sqlcmd i get an error saying :
Error message: 'Server identity is not configured. Please follow the
steps in "Assign an Azure AD identity to your server and add Directory
Reader permission to your identity"
I guess the service principal i running this on needs the directory readers role. I am not sure as i have not seen this error before. I need to be correct before passing the request on to my team members.
Before you can add AAD identities, the managed instance identity must have the "Directory Readers" role in AAD.
For SQL Managed Instance, the Directory Readers role must be assigned
to managed instance identity before you can set up an Azure AD admin
for the managed instance.
Directory Readers role in Azure Active Directory for Azure SQL

Authenticate to SQL Server through PowerShell with MFA (Active Directory Interactive)

I am trying to set up a PowerShell script to enable Always Encrypted on our Azure SQL Server databases. I am following this guide, which offers the following sample code:
# Import the SqlServer module
Import-Module "SqlServer"
# Connect to your database
# Set the valid server name, database name and authentication keywords in the connection string
$serverName = "<Azure SQL server name>.database.windows.net"
$databaseName = "<database name>"
$connStr = "Server = " + $serverName + "; Database = " + $databaseName + "; Authentication = Active Directory Integrated"
$database = Get-SqlDatabase -ConnectionString $connStr
# List column master keys for the specified database.
Get-SqlColumnMasterKey -InputObject $database
I run into problems however with getting the database connection to work. From what it seems the Get-SqlDatabase command from the SqlServer module that is used does not seem to support login through MFA. Our company have enforced this type of login, so I can't seem to find a way around this.
When running Get-SqlDatabase -ConnectionString 'Server=myserver.database.windows.net; Database=myDB; Authentication=Active Directory Interactive;' I receive the following error:
Cannot find an authentication provider for 'ActiveDirectoryInteractive'.
Does SqlServer-module lack the ability to support MFA logins? Or am I missing something else?
Get-SqlDatabase Cmdlet uses the System.Data.SqlClient wherein as per the documentation below values are supported in Authentication Keyword.
Valid values are:
Active Directory Integrated
Active Directory Password
Sql Password
Active Directory Integrated :To use This authentication mode can be, you need to federate the on-premise Active Directory Federation Services (ADFS) with Azure Active Directory in the cloud
Active Directory Password: authentication=ActiveDirectoryPassword can be used to connect to an Azure SQL Database/Synapse Analytics using an Azure AD user name and password.
Sql Password :Use authentication=SqlPassword to connect to a SQL Server using userName/user and password properties.
If you want to Authenticate to Sql Server through PowerShell with MFA you need to use Active Directory Interactive in authentication keyword which is not supported by system.data.sqlclient
Active Directory Interactive:authentication=ActiveDirectoryInteractive can be used to connect to an Azure SQL Database/Synapse Analytics using an interactive authentication flow (multi-factor authentication)
Please note that the System.Data.SqlClient driver, and consequently the Get-SqlDatabase cmdlet, does not support the full range of Azure AD authentication methods. If none of the supported methods works in your environment, using SQL authentication may be the only option.

Access office 365 authentication popup of PowerShell from Windows Form/WPF

I have a following PowerShell script, this scripts connects to my Azure Analysis services. As I execute following script, it opens a popup like image below.
param(
[String]
$envName1
)
$loadInfo1 = [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$server1 = New-Object Microsoft.AnalysisServices.Server
$server1.Connect($envName1)
return $server1
Problem is that I want to execute this PowerShell from my WPF application. I don't understand, how can I access this Popup in my WPF application.
I'm not too sure what you mean by that. However, you need an account to connect to Azure, maybe you signed out or never actually signed in to Visual Studio.
Edit: I finally understand what you mean (slightly). So there are basically two solutions. First one is Azure AD. To connect to Office 355 with PowerShell using the AzureAD module, you’ll first need to install it. You can do so by running Install-Module AzureAD from an administrative PowerShell session. Once you have the module installed, run the Connect-AzureAD cmdlet. Once you do, PowerShell will prompt for your Microsoft ID and password (Work or school account). Once authenticated, you’ll be able to use all of the commands in the module.
Connecting to Office 365 with the MSOnline Module:
Connecting to Office 365 with PowerShell using the MSOnline module requires a little bit more effort. Assuming you have the Microsoft Online Services Sign-In Assistant for IT Professionals RTW software package installed:
Install the MSOnline module from the PowerShell Gallery by running from an administrative PowerShell console:
Install-Module MSOnline (Function)
Once the module is installed, run Get-Module to ensure PowerShell can find the module.
Finally, run the Connect-MsolService cmdlet to authenticate to Azure AD. This will prompt you for your Office 365 credential.

PS cmdlet : Add-SqlAzureAuthenticationContext connect to Azure China

I have a working script via https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/configure-always-encrypted-keys-using-powershell (KeyVault + SQL Azure setup), in "Step 6. Authenticate to Azure, if your column master key is stored in Azure Key Vault.", I run PS "Add-SqlAzureAuthenticationContext -Interactive", but this will pop a dialog connect to Azure US,not Azure CN.
I browsed cmdlet doc, cannot see anything setting environment parameter, how can I let the cmdlet connect to AzureCN?
Thanks,
Cheng

Resources