取得驗證應用程式以從程式碼存取 Azure SQL 資料庫所需的值

適用於:Azure SQL 資料庫

若要從程式碼建立和管理 Azure SQL 資料庫,必須使用 Microsoft Entra ID (先前的 Azure Active Directory) 註冊應用程式。 必須在與您的 Azure SQL 資料庫資源相同的 Microsoft Entra 租用戶中註冊該應用程式。

建立服務主體以從應用程式存取資源

下列範例會建立 Active Directory (AD) 應用程式和我們驗證 C# 應用程式所需的服務主體。 指令碼會輸出上述 C# 範例所需的值。 如需詳細資訊,請參閱使用 Azure PowerShell 建立服務主體以存取資源

重要

SQL Database 仍然支援 PowerShell Azure Resource Manager (RM) 模組,但所有未來的開發都是針對 Az.Sql 模組。 AzureRM 模組在至少 2020 年 12 月之前都還會持續收到 Bug 修正。 Az 模組和 AzureRm 模組中命令的引數本質上完全相同。 如需其相容性的詳細資訊,請參閱新的 Azure PowerShell Az 模組簡介

# 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

另請參閱

使用 C# 在 Azure SQL 資料庫中建立資料庫
使用 Microsoft Entra 驗證連線到 Azure SQL Server