Share via


Abrufen der Client-ID und des Schlüssels für die Verbindung mit der Azure SQL-Datenbank aus dem Code

Gilt für:Azure SQL-Datenbank

Um eine Azure SQL-Datenbank aus Code zu erstellen und zu verwalten, müssen Sie Ihre App mit Microsoft Entra ID (früher Azure Active Directory) registrieren. Die App muss im selben Microsoft Entra-Mandanten wie Ihre Azure SQL-Datenbank Ressource registriert werden.

Erstellen eines Dienstprinzipals für den Zugriff auf Ressourcen aus einer Anwendung

In den folgenden Beispielen werden die Active Directory-Anwendung (AD) und der Dienstprinzipal erstellt, den wir zum Authentifizieren unserer C#-App benötigen. Das Skript gibt Werte aus, die für das vorhergehende C#-Beispiel erforderlich sind. Ausführliche Informationen finden Sie unter Erstellen eines Dienstprinzipals für den Zugriff auf Ressourcen mithilfe von Azure PowerShell.

Wichtig

Das Azure Resource Manager-Modul von PowerShell wird von SQL-Datenbank weiterhin unterstützt, aber alle zukünftigen Entwicklungen erfolgen für das Az.Sql-Modul. Das AzureRM-Modul erhält mindestens bis Dezember 2020 weiterhin Fehlerbehebungen. Die Argumente für die Befehle im Az-Modul und den AzureRm-Modulen sind im Wesentlichen identisch. Weitere Informationen zur Kompatibilität finden Sie in der Einführung in das neue Azure PowerShell Az-Modul.

# sign in to Azure
Connect-AzAccount

# for multiple subscriptions, uncomment and set to the subscription you want to work with
#$subscriptionId = "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"
#Set-AzContext -SubscriptionId $subscriptionId

$appName = "{app-name}" # display name for your app, must be unique in your directory
$uri = "http://{app-name}" # does not need to be a real uri
$secret = "{app-password}"

# create an AAD app
$azureAdApplication = New-AzADApplication -DisplayName $appName -HomePage $Uri -IdentifierUris $Uri -Password $secret

# create a Service Principal for the app
$svcprincipal = New-AzADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId

Start-Sleep -s 15 # to avoid a PrincipalNotFound error, pause here for 15 seconds

# if you still get a PrincipalNotFound error, then rerun the following until successful.
$roleassignment = New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $azureAdApplication.ApplicationId.Guid

# output the values we need for our C# application to successfully authenticate
Write-Output "Copy these values into the C# sample app"

Write-Output "_subscriptionId:" (Get-AzContext).Subscription.SubscriptionId
Write-Output "_tenantId:" (Get-AzContext).Tenant.TenantId
Write-Output "_applicationId:" $azureAdApplication.ApplicationId.Guid
Write-Output "_applicationSecret:" $secret

Weitere Informationen

Erstellen einer Datenbank in Azure SQL-Datenbank mit C#
Herstellen einer Verbindung mit Azure SQL-Datenbank mithilfe der Microsoft Entra-Authentifizierung