Skip to main content

How to Log into Azure SQL with Security Principal

To log into your Azure SQL Database with a Security principal do the following:

  1. Create an Azure AD security group
  2. Add this AAD group as Azure Administrator to your Azure SQL server 
  3. Obtain Access Token
  4. Connect to Azure SQL Server with the access token


for step #3 use this function



#
# Based on
# https://blogs.technet.microsoft.com/stefan_stranger/2018/06/06/connect-to-azure-sql-database-by-obtaining-a-token-from-azure-active-directory-aad/
#

Function Get-AADToken {
[CmdletBinding()]
[OutputType([string])]
PARAM (
[String]$TenantID,
[string]$ServicePrincipalId,
[securestring]$ServicePrincipalPwd
)

Try {
# Set Resource URI to Azure Database
$resourceAppIdURI = 'https://database.windows.net/'

# Set Authority to Azure AD Tenant
$authority = 'https://login.windows.net/' + $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
return $Token
}
Catch {
Throw $_
$ErrorMessage = 'Failed to acquire Azure AD token.'
Write-Error -Message 'Failed to acquire Azure AD token'
}
}


When you have the token to connect to the database is as simple as this



$conn = New-Object System.Data.SqlClient.SQLConnection
$conn.ConnectionString = "Data Source=$SQLServerName.database.windows.net;Initial Catalog=$DatabaseName;Connect Timeout=30"
$conn.AccessToken = $($SPNToken)


And putting all in one piece:

#
# Based on
# https://blogs.technet.microsoft.com/stefan_stranger/2018/06/06/connect-to-azure-sql-database-by-obtaining-a-token-from-azure-active-directory-aad/
#
#
# Prerequisites:
#    1. Azure AD Admin  assigned to the Azure SQL Server (use AAD Group)
#    2. The security principal added to the AAD group (which is Azure Admin for the SQL server)
#
#

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

        # Set Authority to Azure AD Tenant
        $authority = 'https://login.windows.net/' + $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.CreateAuthorizationHeader()
        $Token = $authResult.Result.AccessToken
        return $Token
    }
    Catch {
        Throw $_
        $ErrorMessage = 'Failed to acquire Azure AD token.'
        Write-Error -Message 'Failed to acquire Azure AD token'
    }
}


# Service Principal details
$SPname = "<your SP display name>"
$SPpwd = "<your SP secret>"

# SQL Server and DB
$SQLServerName = "<your Azure SQL server name>"
$DatabaseName = '<your DB name>'

$AzureCtx = Get-AzureRmContext
if (! $AzureCtx) { Connect-AzureRmAccount; $AzureCtx = Get-AzureRmContext }

# Connect to db using SPN Account

$TenantId = $AzureCtx.Tenant.ID
$ServicePrincipalId = $(Get-AzureRmADServicePrincipal -DisplayName $SPname).ApplicationId
$SecureStringPassword = ConvertTo-SecureString -String $SPpwd -AsPlainText -Force


$SPNToken = Get-AADToken -TenantID $TenantId -ServicePrincipalId $ServicePrincipalId -ServicePrincipalPwd $SecureStringPassword

Write-Output "Create SQL ConnectionString"
$conn = New-Object System.Data.SqlClient.SQLConnection
$conn.ConnectionString = "Data Source=$SQLServerName.database.windows.net;Initial Catalog=$DatabaseName;Connect Timeout=30"
$conn.AccessToken = $($SPNToken)

Write-Output "Connect to database and execute SQL script"
$conn.Open()
$query = 'select count(*) as aaaaa from dbo.t1'
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $conn)
$Result = $command.ExecuteScalar()
$Result
$conn.Close()

#end




Comments

Popular posts from this blog

SQL 2014 performance - Local disk vs. Azure Blob vs. Azure VM attached disk

Today I decided to compare SQL 2014 (RTM) performance when running a test against  - a local database (created on  WD7500BPKT - 750 GB 7200 RPM)  - a DB created on a disk attached to the A3 (3 cores, 7 GB) VM in Azure - a DB created on an Azure blob The VM in Azure was created in the US East region using the SQL 2014 template from the gallary provided by Microsoft. All databases were created with a single 10 GB data file (10 GB) and 1GB  log file. On the local SQL instance the DB was created as CREATE DATABASE TestDBonLocal ON     (NAME = file_data1, FILENAME = 'C:\TEMP\filedata1.mdf', SIZE = 10GB, FILEGROWTH = 256 MB )  LOG ON  (NAME = file_log1, FILENAME = 'C:\TEMP\filelog1.ldf', SIZE = 1GB, FILEGROWTH = 32 MB)  On the Azure VM the database on the attached disk (the disk was mapped as drive F:) was created as such CREATE DATABASE TestDBonDisk ON     (NAME = file_data1, FILENAME = 'F:\TMP\filedat...

Create 3-Node Windows 2012 Multi-subnet Cluster

Environment There are two Data centers connected via a WAN link. Two Windows 2012 Servers (called SQLDEV1 and SQLDEV2) are located in the Primary Data Center (on the IP subnet 192.168.79.0/24) and the third server is placed in the Secondary Data Center with the 192.168.69.0/24 subnet. We’ll be creating a three-node Windows cluster with no shared storage on the multi subnet network with a file share witness at the Primary Data Center. We’ll be using a file share witness to protect from the cluster failure in a situation when the network between the Data Centers is unavailable and one of the servers in the Primary Data Center is also down (or being rebooted). The final state will look like depicted above: -           Two Virtual IP’s will be assigned (192.168.76.218 and 192.168.69.134) to the cluster -           The servers at the Primary Data Center will have a vote (Vote=1) and the ...

SQL 2012 AlwaysOn: Synchronous vs. Asynchronous commit. Performance impact

Recently I've had a chance to build a 3-server AlwaysOn environment distributed between the primary and secondary data centers. The configuration looks like this: Primary Data Center                         Secondary Data Center                        SQLDEV1                                        SQLDEV3          SQLDEV2 The availability group was crated with synchronous commit replicas on SQLDEV1 and SQLDEV2 and the replica on SQLDEV3 was configured for asynchronous commit. The link between the data centers was not great and when I pinged SQLDEV3 from SQLDEV1 I got these results Approximate round trip times in milli-seconds:     Minimum = 39ms, Maximum = 63ms, Average = 42ms I also created a very simp...