Freigeben über


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-DatenbankSQL-Datenbank in Fabric

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 Microsoft Entra-Anwendung 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 PowerShell-Modul Azure Resource Manager (AzureRM) wurde am 29. Februar 2024 nicht mehr unterstützt. Alle zukünftigen Entwicklungen sollten das Az.Sql-Modul verwenden. Benutzern wird empfohlen, von AzureRM zum Az PowerShell-Modul zu migrieren, um fortgesetzte Unterstützung und Updates sicherzustellen. Das AzureRM-Modul wird nicht mehr verwaltet oder unterstützt. Die Argumente für die Befehle im Az PowerShell-Modul und in den AzureRM-Modulen sind wesentlich identisch. Weitere Informationen zur Kompatibilität finden Sie unter Einführung in das neue Az PowerShell-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