App Service では、Azure の高度にスケーラブルな自己適用型の Web ホスティング サービスを提供しています。 さらに、以下のような Azure データベースへのアクセスをセキュリティ保護するためのターンキー ソリューションであるマネージド ID もアプリ向けに提供しています。
App Service のマネージド ID を使用すると、接続文字列内の認証情報などのシークレットをアプリから排除することで、アプリのセキュリティを強化できます。 このチュートリアルでは、マネージド ID を使用して App Service から上記のデータベースに接続する方法について説明します。
学習内容
- Microsoft Entra ユーザーを Azure データベースの管理者として構成します。
- データベースに Microsoft Entra ユーザーとして接続します。
- App Service アプリのシステム割り当てまたはユーザー割り当てマネージド ID を構成します。
- データベースへのアクセスをマネージド ID に付与します。
- マネージド ID を使用して、コード (.NET Framework 4.8、.NET 6、Node.js、Python、Java) から Azure データベースに接続します。
- Microsoft Entra ユーザーを使用して、開発環境から Azure データベースに接続します。
Azure サブスクリプションをお持ちでない場合は、開始する前に Azure 無料アカウントを作成してください。
前提条件
- .NET、Node.js、Python、または Java に基づいて、App Service でアプリを作成します。
- Azure SQL Database、Azure Database for MySQL、または Azure Database for PostgreSQL でデータベース サーバーを作成します。
- 標準的な接続パターン (ユーザー名とパスワード) を熟知し、App Service アプリから選択したデータベースに正常に接続できるようになる必要があります。
Azure CLI の環境を準備します。
1.Service Connector パスワードレス拡張機能をインストールする
最新の Azure CLI 用 Service Connector パスワードレス拡張機能をインストールします。
az extension add --name serviceconnector-passwordless --upgrade
Note
az version
を実行して、拡張機能 "serviceconnector-passwordless" バージョンが "2.0.2" 以降であることを確認してください。 拡張機能のバージョンをアップグレードするには、最初に Azure CLI のアップグレードが必要になる場合があります。
2.パスワードレス接続を作成する
次に、Service Connector を使用してパスワードレス接続を作成します。
ヒント
Azure portal は、次のコマンドの作成に役立ちます。 Azure portal で、[Azure App Service] リソースに移動し、左側のメニューから [サービス コネクタ] を選択し、[作成] を選択します。 フォームに必要なすべてのパラメーターを入力します。 Azure は自動的に接続作成コマンドが生成します。このコマンドは、コピーして CLI で使用したり、Azure Cloud Shell で実行したりできます。
次の Azure CLI コマンドでは、--client-type
パラメーターを使用します。
必要に応じて、az webapp connection create sql -h
を実行してサポートされているクライアントの種類を取得します。
クライアントの種類を選択し、対応するコマンドを実行します。 次のプレースホルダーを実際の情報に置き換えてください。
az webapp connection create sql \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <sql-group-name> \
--server <sql-name> \
--database <database-name> \
--user-identity client-id=<client-id> subs-id=<subscription-id> \
--client-type <client-type>
az webapp connection create sql \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <sql-name> \
--database <database-name> \
--system-identity \
--client-type <client-type>
Note
Azure Database for MySQL - フレキシブル サーバーの場合は、まず Microsoft Entra 認証を手動で設定する必要があります。これには、個別のユーザー割り当てマネージド ID と特定の Microsoft Graph アクセス許可が必要です。 この手順は自動化できません。
手動で Azure Database for MySQL - フレキシブル サーバーの Microsoft Entra 認証を設定します。
必要に応じて、コマンド az webapp connection create mysql-flexible -h
を実行してサポートされているクライアントの種類を取得します。
クライアントの種類を選択し、対応するコマンドを実行します。 次の Azure CLI コマンドでは、--client-type
パラメーターを使用します。
az webapp connection create mysql-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <mysql-name> \
--database <database-name> \
--user-identity client-id=XX subs-id=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type <client-type>
az webapp connection create mysql-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <mysql-name> \
--database <database-name> \
--system-identity mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type <client-type>
次の Azure CLI コマンドでは、--client-type
パラメーターを使用します。
必要に応じて、コマンド az webapp connection create postgres-flexible -h
を実行して、サポートされているすべてのクライアントの種類の一覧を取得します。
クライアントの種類を選択し、対応するコマンドを実行します。
az webapp connection create postgres-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <postgresql-name> \
--database <database-name> \
--user-identity client-id=XX subs-id=XX \
--client-type java
az webapp connection create postgres-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <postgresql-name> \
--database <database-name> \
--system-identity \
--client-type <client-type>
事前に作成されたテーブルへのアクセス許可を付与する
次に、Service Connector を使用する前に PostgreSQL フレキシブル サーバーでテーブルとシーケンスを作成している場合、所有者として接続し、Service Connector によって作成された <aad-username>
にアクセス許可を付与する必要があります。 Service Connector によって設定された接続文字列または構成からのユーザー名は aad_<connection name>
のようになるはずです。 Azure portal を使用する場合、Service Type
列の横にある展開ボタンを選択し、値を取得します。 Azure CLI を使用する場合、CLI コマンドの出力の configurations
をチェックします。
次に、クエリを実行してアクセス許可を付与します
az extension add --name rdbms-connect
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \"<aad-username>\";GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO \"<aad username>\";"
<owner-username>
と <owner-password>
は、他のユーザーにアクセス許可を付与できる既存のテーブルの所有者です。
<aad-username>
は、サービス コネクタによって作成されたユーザーです。 これらを実際の値に置き換えます。
次のコマンドを使用して結果を検証します。
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "SELECT distinct(table_name) FROM information_schema.table_privileges WHERE grantee='<aad-username>' AND table_schema='public';" --output table
この Service Connector コマンドは、バックグラウンドで次のタスクを完了します。
- システム割り当てマネージド ID を有効にするか、Azure App Service によってホストされているアプリ
<server-name>
のユーザー ID を割り当てます。
- Microsoft Entra 管理者を現在サインインしているユーザーに設定します。
- システム割り当てマネージド ID またはユーザー割り当てマネージド ID のデータベース ユーザーを追加します。 データベース
<database-name>
のすべての特権をこのユーザーに付与します。 ユーザー名は、前のコマンド出力の接続文字列で確認できます。
-
AZURE_MYSQL_CONNECTIONSTRING
、AZURE_POSTGRESQL_CONNECTIONSTRING
、または AZURE_SQL_CONNECTIONSTRING
という名前の構成を、データベースの種類に基づいて Azure リソースに設定します。
- App Service の場合、構成は [アプリの設定] ブレードで設定されます。
接続の作成時に問題が発生した場合は、「トラブルシューティング」を参照してください。
3. コードを変更する
依存関係をインストールします。
dotnet add package Microsoft.Data.SqlClient
サービス コネクタによって追加された環境変数から Azure SQL Database 接続文字列を取得します。
using Microsoft.Data.SqlClient;
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity:"Server=tcp:<server-name>.database.windows.net;Database=<database-name>;Authentication=Active Directory Default;TrustServerCertificate=True"
// For user-assigned managed identity: "Server=tcp:<server-name>.database.windows.net;Database=<database-name>;Authentication=Active Directory Default;User Id=<client-id-of-user-assigned-identity>;TrustServerCertificate=True"
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
詳細については、「Active Directory Managed Identity 認証の使用」を参照してください。
pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
サービス コネクタによって追加された環境変数から Azure SQL Database 接続文字列を取得します。
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class Main {
public static void main(String[] args) {
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};msiClientId={UserAssignedMiClientId};authentication=ActiveDirectoryMSI;"
String connectionString = System.getenv("AZURE_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
詳細については、「Microsoft Entra 認証を使用して接続する」を参照してください。
依存関係をインストールします。
python -m pip install pyodbc
サービス コネクタによって追加された環境変数から Azure SQL Database 接続構成を取得します。 使用する認証型のコード スニペットの一部をコメント解除します。
import os;
import pyodbc
server = os.getenv('AZURE_SQL_SERVER')
port = os.getenv('AZURE_SQL_PORT')
database = os.getenv('AZURE_SQL_DATABASE')
authentication = os.getenv('AZURE_SQL_AUTHENTICATION') # The value should be 'ActiveDirectoryMsi'
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity.
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server={server},{port};Database={database};Authentication={authentication};Encrypt=yes;'
# For user-assigned managed identity.
# client_id = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server={server},{port};Database={database};UID={client_id};Authentication={authentication};Encrypt=yes;'
conn = pyodbc.connect(connString)
別の方法として、アクセス トークンを使用して Azure SQL Database に接続することもできます。「Azure SQL Database との間でパスワードレス接続を使うように Python アプリケーションを移行する」を参照してください。
- 依存関係をインストールします。
npm install mssql
- サービス コネクタによって追加された環境変数から Azure SQL Database 接続構成を取得します。 使用する認証型のコード スニペットの一部をコメント解除します。
import sql from 'mssql';
const server = process.env.AZURE_SQL_SERVER;
const database = process.env.AZURE_SQL_DATABASE;
const port = parseInt(process.env.AZURE_SQL_PORT);
const authenticationType = process.env.AZURE_SQL_AUTHENTICATIONTYPE;
// Uncomment the following lines according to the authentication type.
// For system-assigned managed identity.
// const config = {
// server,
// port,
// database,
// authentication: {
// authenticationType
// },
// options: {
// encrypt: true
// }
// };
// For user-assigned managed identity.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId
// }
// };
this.poolconnection = await sql.connect(config);
詳細については、「Microsoft SQL Server に対するクライアント プログラミングのホーム ページ」を参照してください。
その他のコード サンプルについては、「Service Connector を使用してデータベース サービスへのパスワードレス接続を作成する」を参照してください。
コード内の Azure Database for MySQL への接続では、すべての言語スタックの DefaultAzureCredential
パターンに従います。
DefaultAzureCredential
は、開発環境と Azure 環境の両方に適応できるだけの柔軟性を備えています。 ローカルで実行しているとき、任意の環境 (Visual Studio、Visual Studio Code、Azure CLI、Azure PowerShell) からログインしている Azure ユーザーを取得できます。 Azure で実行しているとき、マネージド ID が取得されます。 そのため、開発時と運用時の両方でデータベースへの接続が可能です。 パターンは次のとおりです。
- Azure ID クライアント ライブラリから
DefaultAzureCredential
をインスタンス化します。 ユーザー割り当て ID を使用している場合は、ID のクライアント ID を指定します。
- Azure Database for MySQL のアクセストークン
https://ossrdbms-aad.database.windows.net/.default
を取得します。
- トークンを接続文字列に追加します。
- 接続を開きます。
.NET については、Azure.Identity などのクライアント ライブラリを使用して、マネージド ID のアクセス トークンを取得します。 次に、アクセス トークンをパスワードとして使用してデータベースに接続できます。 次のコードを使用する場合は、使用する認証型に対応するコード スニペットの一部をコメント解除します。
using Azure.Core;
using Azure.Identity;
using MySqlConnector;
// Uncomment the following lines according to the authentication type.
// For system-assigned managed identity.
// var credential = new DefaultAzureCredential();
// For user-assigned managed identity.
// var credential = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// });
var tokenRequestContext = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.windows.net/.default" });
AccessToken accessToken = await credential.GetTokenAsync(tokenRequestContext);
// Open a connection to the MySQL server using the access token.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING")};Password={accessToken.Token}";
using var connection = new MySqlConnection(connectionString);
Console.WriteLine("Opening connection using access token...");
await connection.OpenAsync();
// do something
pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
環境変数から接続文字列を取得し、データベースに接続するためのプラグイン名を追加します。
String url = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.mysql.AzureMysqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&defaultAuthenticationPlugin=" +
pluginName + "&authenticationPlugins=" + pluginName);
詳細については、「Azure Database for MySQL - フレキシブル サーバーで Java と JDBC を使用する」を参照してください。
依存関係をインストールします。
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
azure-identity
ライブラリからのアクセス トークンを使用して認証します。 Service Connector によって追加された環境変数から接続情報を取得します。 次のコードを使用する場合は、使用する認証型に対応するコード スニペットの一部をコメント解除します。
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import mysql.connector
import os
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity.
# cred = ManagedIdentityCredential()
# For user-assigned managed identity.
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# open connect to Azure MySQL with the access token.
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token
cnx = mysql.connector.connect(user=user,
password=password,
host=host,
database=database)
cnx.close()
依存関係をインストールします。
npm install --save @azure/identity
npm install --save mysql2
Service Connector によって追加された環境変数からの Azure MySQL データベース情報と @azure/identity
を使用して、アクセス トークンを取得します。 次のコードを使用する場合は、使用する認証型に対応するコード スニペットの一部をコメント解除します。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines according to the authentication type.
// for system-assigned managed identity
// const credential = new DefaultAzureCredential();
// for user-assigned managed identity
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: accessToken.token,
database: process.env.AZURE_MYSQL_DATABASE,
port: process.env.AZURE_MYSQL_PORT,
ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database');
});
その他のコード サンプルについては、「Service Connector を使用してデータベース サービスへのパスワードレス接続を作成する」を参照してください。
コード内の Azure Database for PostgreSQL への接続では、すべての言語スタックの DefaultAzureCredential
パターンに従います。
DefaultAzureCredential
は、開発環境と Azure 環境の両方に適応できるだけの柔軟性を備えています。 ローカルで実行しているとき、任意の環境 (Visual Studio、Visual Studio Code、Azure CLI、Azure PowerShell) からログインしている Azure ユーザーを取得できます。 Azure で実行しているとき、マネージド ID が取得されます。 そのため、開発時と運用時の両方でデータベースへの接続が可能です。 パターンは次のとおりです。
- Azure ID クライアント ライブラリから
DefaultAzureCredential
をインスタンス化します。 ユーザー割り当て ID を使用している場合は、ID のクライアント ID を指定します。
- Azure Database for PostgreSQL のアクセス トークン
https://ossrdbms-aad.database.windows.net/.default
を取得します。
- トークンを接続文字列に追加します。
- 接続を開きます。
.NET については、Azure.Identity などのクライアント ライブラリを使用して、マネージド ID のアクセス トークンを取得します。 次に、アクセス トークンをパスワードとして使用してデータベースに接続できます。 次のコードを使用する場合は、使用する認証型に対応するコード スニペットの一部をコメント解除します。
using Azure.Identity;
using Azure.Core;
using Npgsql;
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// }
// );
// Acquire the access token.
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.windows.net/.default"
}));
// Combine the token with the connection string from the environment variables provided by Service Connector.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING")};Password={accessToken.Token}";
// Establish the connection.
using (var connection = new NpgsqlConnection(connectionString))
{
Console.WriteLine("Opening connection using access token...");
connection.Open();
}
pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.5</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
環境変数から接続文字列を取得し、データベースに接続するためのプラグイン名を追加します。
import java.sql.*;
String url = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
String pluginName = "com.Azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&authenticationPluginClassName=" + pluginName);
詳細については、次のリソースを参照してください。
依存関係をインストールします。
pip install azure-identity
pip install psycopg2-binary
azure-identity
ライブラリから取得したアクセス トークンで認証し、トークンをパスワードとして使います。 Service Connector によって追加された環境変数から接続情報を取得します。 次のコードを使用する場合は、使用する認証型に対応するコード スニペットの一部をコメント解除します。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# Acquire the access token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
conn_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
conn = psycopg2.connect(conn_string + ' password=' + accessToken.token)
詳細については、次のリソースを参照してください。
依存関係をインストールします。
npm install --save @azure/identity
npm install --save pg
コードで、@azure/identity
経由でアクセス トークンを取得し、Service Connector サービスによって追加された環境変数から PostgreSQL 接続情報を取得します。 これらを組み合わせて接続を確立します。 次のコードを使用する場合は、使用する認証型に対応するコード スニペットの一部をコメント解除します。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// Acquire the access token.
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
// Use the token and the connection information from the environment variables added by Service Connector to establish the connection.
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: accesstoken.token,
database: process.env.AZURE_POSTGRESQL_DATABASE,
port: Number(process.env.AZURE_POSTGRESQL_PORT) ,
ssl: process.env.AZURE_POSTGRESQL_SSL
});
await client.connect();
await client.end();
})();
その他のコード サンプルについては、「Service Connector を使用してデータベース サービスへのパスワードレス接続を作成する」を参照してください。
4. 開発環境をセットアップする
このサンプル コードは DefaultAzureCredential
を使用して Azure データベースの使用可能トークンを Microsoft Entra ID から取得して、データベース接続に追加します。
DefaultAzureCredential
はカスタマイズ可能ですが、既に既定で万能で使用できます。 トークンをサインインした Microsoft Entra ユーザーから取得するかマネージド ID から取得するかは、開発環境でローカルで実行するか、App Service で実行するかによって異なります。
これ以上変更することなく、あなたのコードは Azure で実行する準備ができました。 ただしコードをローカルでデバッグするには、サインインした Microsoft Entra ユーザーが開発環境に必要です。 この手順では、Microsoft Entra ユーザーでサインインして、お好きな環境を構成します。
Visual Studio for Windows は Microsoft Entra 認証と統合されています。 Visual Studio で開発とデバッグを有効にするには、メニューから [ファイル]>[アカウント設定] を選択し、[サインイン] または [追加] を選択して、Visual Studio で Microsoft Entra ユーザーを追加してください。
Azure サービス認証用に Microsoft Entra ユーザーを設定するには、メニューから [ツール]>[オプション] の順に選択した後、[Azure サービス認証]>[アカウントの選択] の順に選択してください。 追加した Microsoft Entra ユーザーを選択し、[OK] を選択してください。
Visual Studio for Mac は Microsoft Entra 認証と統合されて "いません"。 ただし、後で使用する Azure ID クライアント ライブラリでは、Azure CLI からトークンを取得することもできます。 Visual Studio での開発とデバッグを可能にするには、ご使用のローカル コンピューター上に Azure CLI をインストールします。
ご自分の Microsoft Entra ユーザーを使用して、次のコマンドで Azure CLI にサインインしてください。
az login --allow-no-subscriptions
Visual Studio Code は、Azure 拡張機能を介して Microsoft Entra 認証と統合されています。 Visual Studio Code で Azure Tools 拡張機能をインストールします。
Visual Studio Code の アクティビティ バーで、Azure のロゴを選択します。
App Service エクスプローラーで、 [Azure にサインイン] を選択し、指示に従います。
後で使用する Azure ID クライアント ライブラリでは、Azure CLI のトークンを使用できます。 コマンド ライン ベースの開発を有効にするには、ローカル コンピューターに Azure CLI をインストールします。
ご自分の Microsoft Entra ユーザーを使用して、次のコマンドで Azure にサインインしてください。
az login --allow-no-subscriptions
後で使用する Azure ID クライアント ライブラリは、Azure PowerShell のトークンが使用できます。 コマンド ライン ベースの開発を有効にするには、ローカル コンピューターに Azure PowerShellをインストールします。
ご自分の Microsoft Entra ユーザーを使用して、次のコマンドレットで Azure CLI にサインインしてください。
Connect-AzAccount
Microsoft Entra 認証用に開発環境を設定する方法の詳細については.NET 用 Azure Identity クライアント ライブラリに関するページを参照してください。
これで、Microsoft Entra 認証を使用し、SQL Database をバックエンドとして利用して、ご自分のアプリを開発およびデバッグする準備ができました。
5. テストして発行する
コードを開発環境で実行します。 コードは、環境内でサインインした Microsoft Entra ユーザーを使って、バックエンド データベースに接続します。 このユーザーがデータベースにアクセスできる理由は、データベースの Microsoft Entra 管理者として構成されているからです。
コードを Azure に、望ましい発行方法を使用して発行します。 App Service では、コードはアプリのマネージド ID を使用してバックエンド データベースに接続します。
よく寄せられる質問
マネージド ID は SQL Server をサポートしていますか?
はい。 詳細については、以下を参照してください:
エラー Login failed for user '<token-identified principal>'.
が発生します
トークンを要求しようとしているマネージド ID が、Azure データベースへのアクセスを許可されていません。
App Service 認証または関連しているアプリ登録に変更を加えました。 古いトークンをまだ取得するのはなぜですか?
マネージド ID のバックエンド サービスは、トークン キャッシュも管理します。トークン キャッシュでは、有効期限が切れたときにのみターゲット リソースのトークンが更新されます。 アプリでトークンを取得しようとした後に構成を変更すると、キャッシュされたトークンの期限が切れるまで、更新されたアクセス許可で新しいトークンが実際には取得されません。 この問題を回避するには、新しい InPrivate (Edge)/private (Safari)/Incognito (Chrome) ウィンドウで変更をテストするのが最もよい方法です。 そうすれば、新しい認証済みセッションから始めることができます。
マネージド ID を Microsoft Entra グループに追加するにはどうすればよいですか?
必要に応じて、Microsoft Entra グループに ID を追加し、ID ではなく Microsoft Entra グループにアクセスを許可することができます。 たとえば、次のコマンドは、前の手順のマネージド ID を myAzureSQLDBAccessGroup という名前の新しいグループに追加します。
groupid=$(az ad group create --display-name myAzureSQLDBAccessGroup --mail-nickname myAzureSQLDBAccessGroup --query objectId --output tsv)
msiobjectid=$(az webapp identity show --resource-group <group-name> --name <app-name> --query principalId --output tsv)
az ad group member add --group $groupid --member-id $msiobjectid
az ad group member list -g $groupid
Microsoft Entra グループのデータベース アクセス許可を付与するには、それぞれのデータベースの種類に関するドキュメントを参照してください。
エラー SSL connection is required. Please specify SSL options and retry
が発生します。
Azure データベースへの接続に追加の設定が必要であり、このチュートリアルのスコープを超えています。 詳細については、以下のいずれかのリンクを参照してください。
Azure Database for PostgreSQL (単一サーバー) で TLS 接続を構成するzure Database for MySQL に安全に接続するためにアプリケーションで SSL 接続を構成する
Service Connector で、アプリ ID にアクセス権を付与するには、データベースへのネットワーク アクセスが必要です。 Azure portal で Web App + Database テンプレートを使用して、既定でセキュリティで保護されたアプリとデータベースのアーキテクチャを作成すると、そのアーキテクチャにより、データベースへのネットワーク アクセスはロックダウンされ、仮想ネットワーク内からの接続のみが許可されます。 これは Azure Cloud Shell の場合も当てはまります。 ただし、仮想ネットワークに Cloud Shell をデプロイしてから、その Cloud Shell で Service Connector コマンドを実行することはできます。
次のステップ
ここで学習した内容は次のとおりです。
- Microsoft Entra ユーザーを Azure データベースの管理者として構成します。
- データベースに Microsoft Entra ユーザーとして接続します。
- App Service アプリのシステム割り当てまたはユーザー割り当てマネージド ID を構成します。
- データベースへのアクセスをマネージド ID に付与します。
- マネージド ID を使用して、コード (.NET Framework 4.8、.NET 6、Node.js、Python、Java) から Azure データベースに接続します。
- Microsoft Entra ユーザーを使用して、開発環境から Azure データベースに接続します。