次の方法で共有


コードから Azure SQL Database にアクセスするアプリケーションを認証するための必要な値を取得する

適用対象:Azure SQL DatabaseMicrosoft Fabric SQL Database

コードから Azure SQL Database を作成して管理するには、アプリを Microsoft Entra ID (旧称 Azure Active Directory) に登録する必要があります。 アプリは、Azure SQL Database リソースと同じ Microsoft Entra テナントに登録する必要があります。

アプリケーションからリソースにアクセスするためのサービス プリンシパルの作成

次の例を実行すると、Microsoft Entra アプリケーションのほか、C# アプリの認証に必要なサービス プリンシパルが作成されます。 このスクリプトによって、上記の C# のサンプルに必要な値が出力されます。 詳細については、「 リソースにアクセスするためのサービス プリンシパルを Azure PowerShell で作成する」を参照してください。

重要

PowerShell Azure Resource Manager (AzureRM) モジュールは、2024 年 2 月 29 日に非推奨になりました。 今後のすべての開発では、Az.Sql モジュールを使用する必要があります。 ユーザーは、引き続きサポートと更新を行うために、AzureRM から Az PowerShell モジュールに移行することをお勧めします。 AzureRM モジュールは維持またはサポートされなくなりました。 Az PowerShell モジュールと AzureRM モジュールのコマンドの引数は、ほぼ同じです。 互換性の詳細については、「新しい Az PowerShell モジュールの概要」を参照してください。

# 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 Database にデータベースを作成する
Microsoft Entra 認証を使用して SQL Server に接続する