获取对应用程序进行身份验证所需的值以便从代码访问 Azure SQL 数据库

适用于:Azure SQL 数据库

要从代码创建和管理 Azure SQL 数据库,则必须使用 Microsoft Entra ID(旧称 Azure Active Directory)注册应用。 应用必须在与 Azure SQL 数据库资源相同的 Microsoft Entra 租户中注册。

创建服务主体以便从应用程序访问资源

以下示例将创建对 C# APP 进行身份验证时所需的 Microsoft Entra 应用程序和服务主体。 该脚本输出我们需要用于前面 C# 示例的值。 有关详细信息,请参阅使用 Azure PowerShell 创建服务主体以访问资源

重要

PowerShell Azure 资源管理器(AzureRM)模块已于 2024 年 2 月 29 日弃用。 所有未来的开发都应使用 Az.Sql 模块。 建议用户从 AzureRM 迁移到 Az PowerShell 模块,以确保持续支持和更新。 不再维护或支持 AzureRM 模块。 Az PowerShell 模块和 AzureRM 模块中命令的参数基本相同。 有关兼容性的详细信息,请参阅 介绍新的 Az PowerShell 模块

# sign in to Azure
Connect-AzAccount -Environment AzureChinaCloud

# 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

另请参阅

在 Azure SQL 数据库中使用 C# 创建数据库
使用 Microsoft Entra 身份验证连接到 Azure SQL 数据库