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

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.

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)

SQL Connect using PowerShell

I'm unable to connect to SQL Server without passing password.
I have created a service account user in Active Directory and created a new login user for same in SQL Server, providing db_creator server role to it.
I then created a new database Testdb and provided db_reader & db_writer in user mapping. I need to run the PowerShell script from different computer for SQL authentication.
(https://i.stack.imgur.com/qJTpn.jpg)(https://i.stack.imgur.com/DCspp.jpg)(https://i.stack.imgur.com/LTcz2.jpg)
I am using this connection string for SQL Server authentication:
(https://i.stack.imgur.com/TIT9M.jpg)
I need to connect to SQL Server without passing password from different computers using that service account.

"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

Connect to Azure database with DataGrip - Active Directory

I am trying to connect to Azure database via DataGrip using Active Directory connection (Note: not Active directory - password)
I followed accepted answer from this
I set integratedSecurity=false and authentication=ActiveDirectoryIntegrated.
When trying to connect to Test Connection I get error message
Connection to Azure SQL Database failed. Cannot set "Authetication" with "IntegratedSecurity" set to "true".
Is it some kind of bug that can be repaired, if so how could I solve this issue?
Edit:
More information:
On Azure Portal I can see that this is SQL database.
Server name ends with database.windows.net.
When I try to connect via Connection String (in Data Grip Add data from URL) generated by Azure I am not able to connect also.
The DataGrip support us using Azure Active Directory Authentication. Please see: Microsoft Azure .
You can get the connect string (URL) with Active Directory integrated authentication from Portal:
Replace the URL with the Connect string(Active Directory integrated authentication):
Hope this helps.
There is a lot of confusion around terminology here.
In short, the connection string attribute Integrated Security=true indicates you want to use "windows authentication". This type of authentication might be supported by any Azure SQL (anything whose hostname ends in database.windows.net). Azure SQL only supports Azure Active Directory authentication, butit might be possible to implement single sign on between a windows domain account and Azure Active Directory.

Azure Automation Runbook ADAL SQL support

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.

Resources