次の方法で共有


Azure Database for PostgreSQL を Service Connector と統合する

この記事では、Service Connector を使用してアプリを Azure Database for PostgreSQL に接続するために使用できる、サポートされている認証方法、クライアント、サンプル コードについて説明します。 この記事では、サービス接続の作成時に取得した既定の環境変数の名前、値、構成についても説明します。

サポートされているコンピューティング サービス

Service Connector を使用すると、次のコンピューティング サービスを Azure Database for PostgreSQL に接続できます。

  • Azure App Service
  • Azure Container Apps
  • Azure Functions
  • Azure Kubernetes Service (AKS)
  • Azure Spring Apps

サポートされている認証の種類とクライアントの種類

次の表は、Service Connector を使用してコンピューティング サービスを Azure Database for PostgreSQL に接続するためにサポートされている認証方法とクライアントの組み合わせを示しています。 "はい" はその組み合わせがサポートされていることを示し、"いいえ" はサポートされていないことを示します。

クライアントの種類 システム割り当てマネージド ID ユーザー割り当てマネージド ID シークレット/接続文字列 サービス プリンシパル
.NET はい はい はい はい
Go (pg) はい はい はい はい
Java (JDBC) はい はい はい はい
Java - Spring Boot (JDBC) はい はい はい はい
Node.js (pg) はい はい はい はい
PHP (ネイティブ) はい はい はい はい
Python (psycopg2) はい はい はい はい
Python-Django はい はい はい はい
Ruby (ruby-pg) はい はい はい はい
None はい はい はい はい

Azure CLI では、システム割り当てマネージド ID、ユーザー割り当てマネージド ID、サービス プリンシパルのみがサポートされています。

既定の環境変数名またはアプリケーション プロパティとサンプル コード

接続の認証の種類とクライアントの種類に応じて、次の表の接続の詳細とサンプル コードを参照します。 名前付け規則の詳細については、「Service Connector の内部構造」を参照してください。

システム割り当てマネージド ID

既定の環境変数名 説明 値の例
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL 接続文字列 Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

サンプル コード

システム割り当てマネージド ID を使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。

.NET の場合、パスワードレス接続をサポートするためのプラグインやライブラリはありません。 Azure.Identity のようなクライアント ライブラリを使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得できます。 次に、アクセス トークンをパスワードとして使用してデータベースに接続できます。 次のコードを使用する場合は、コード スニペットで、使用する認証の種類に対応する部分をコメント解除します。

using Azure.Identity;
using Azure.Core;
using Npgsql;

// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();

// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
//     new DefaultAzureCredentialOptions
//     {
//         ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
//     }
// );

// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);

// 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();
}

次に、サービス コネクタを使用する前に PostgreSQL フレキシブル サーバーでテーブルとシーケンスを作成している場合、所有者として接続し、サービス コネクタによって作成された <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

ユーザー割り当てマネージド ID

既定の環境変数名 説明 値の例
AZURE_POSTGRESQL_CLIENTID クライアント ID <identity-client-ID>
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL 接続文字列 Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

サンプル コード

ユーザー割り当てマネージド ID を使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。

.NET の場合、パスワードレス接続をサポートするためのプラグインやライブラリはありません。 Azure.Identity のようなクライアント ライブラリを使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得できます。 次に、アクセス トークンをパスワードとして使用してデータベースに接続できます。 次のコードを使用する場合は、コード スニペットで、使用する認証の種類に対応する部分をコメント解除します。

using Azure.Identity;
using Azure.Core;
using Npgsql;

// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();

// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
//     new DefaultAzureCredentialOptions
//     {
//         ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
//     }
// );

// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);

// 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();
}

次に、サービス コネクタを使用する前に PostgreSQL フレキシブル サーバーでテーブルとシーケンスを作成している場合、所有者として接続し、サービス コネクタによって作成された <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

接続文字列

警告

Microsoft では、利用可能な最も安全な認証フローを使用することをお勧めします。 この手順で説明する認証フローは、アプリケーションに対する非常に高い信頼が必要であり、他のフローには存在しないリスクを伴います。 このフローは、マネージド ID など、より安全な他のフローが利用できない場合にのみ使用してください。

既定の環境変数名 説明 値の例
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL 接続文字列 Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

サンプル コード

接続文字列を使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。

  1. Npgsql ガイダンスに従って依存関係をインストールする
  2. コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続文字列を取得します。
    using System;
    using Npgsql;
    
    string connectionString = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING");
    using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
    {
        connection.Open();
    }
    

サービス プリンシパル

既定の環境変数名 説明 値の例
AZURE_POSTGRESQL_CLIENTID クライアント ID <client-ID>
AZURE_POSTGRESQL_CLIENTSECRET クライアント シークレット <client-secret>
AZURE_POSTGRESQL_TENANTID テナント ID <tenant-ID>
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL 接続文字列 Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

サンプル コード

サービス プリンシパルを使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。

.NET の場合、パスワードレス接続をサポートするためのプラグインやライブラリはありません。 Azure.Identity のようなクライアント ライブラリを使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得できます。 次に、アクセス トークンをパスワードとして使用してデータベースに接続できます。 次のコードを使用する場合は、コード スニペットで、使用する認証の種類に対応する部分をコメント解除します。

using Azure.Identity;
using Azure.Core;
using Npgsql;

// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();

// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
//     new DefaultAzureCredentialOptions
//     {
//         ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
//     }
// );

// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);

// 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();
}

次に、サービス コネクタを使用する前に PostgreSQL フレキシブル サーバーでテーブルとシーケンスを作成している場合、所有者として接続し、サービス コネクタによって作成された <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 の詳細については、以下のチュートリアルに従ってください。