Dela via


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 DatabaseSQL-databas i Fabric

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 Microsoft Entra-programmet och tjänstehuvudnamnet som behövs för att autentisera vår C#-app. Skriptet matar ut värden som vi behöver för föregående C#-exempel. Detaljerad information finns i Använda Azure PowerShell för att skapa ett huvudnamn för tjänsten för att komma åt resurser.

Viktig

PowerShell Azure Resource Manager-modulen (AzureRM) blev föråldrad den 29 februari 2024. All framtida utveckling bör använda Az.Sql-modulen. Användare rekommenderas att migrera från AzureRM till Az PowerShell-modulen för att säkerställa fortsatt support och uppdateringar. AzureRM-modulen underhålls inte längre eller stöds inte längre. Argumenten för kommandona i Az PowerShell-modulen och i AzureRM-modulerna är i stort sätt identiska. Mer information om deras kompatibilitet finns i Introduktion till den nya Az PowerShell-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