Hämta de värden som krävs för att autentisera ett program för att få åtkomst till Azure SQL Database från kod

Gäller för:Azure SQL Database

Om du vill skapa och hantera en Azure SQL Database från kod måste du registrera din app med Microsoft Entra-ID (tidigare Azure Active Directory). Appen måste vara registrerad i samma Microsoft Entra-klientorganisation som din Azure SQL Database-resurs.

Skapa ett huvudnamn för tjänsten för att komma åt resurser från ett program

I följande exempel skapas active directory-programmet (AD) och tjänstens huvudnamn som vi behöver för att autentisera vår C#-app. Skriptet matar ut värden som vi behöver för det föregående C#-exemplet. Detaljerad information finns i Skapa ett tjänstobjekt med Azure PowerShell för att komma åt resurser.

Viktigt!

Modulen PowerShell Azure Resource Manager (RM) stöds fortfarande av SQL Database, men all framtida utveckling gäller för Az.Sql-modulen. AzureRM-modulen fortsätter att ta emot felkorrigeringar fram till åtminstone december 2020. Argumenten för kommandona i Az-modulen och i AzureRm-modulerna är väsentligen identiska. Mer information om deras kompatibilitet finns i Introduktion till den nya Azure PowerShell Az-modulen.

# 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

Se även

Skapa en databas i Azure SQL Database med C#
Anslut till Azure SQL Database med hjälp av Microsoft Entra-autentisering