你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用服务连接器集成 Azure Database for PostgreSQL

本文介绍支持的身份验证方法、客户端和示例代码,可用于使用服务连接器将应用连接到 Azure Database for PostgreSQL。 在本文中,还将找到创建服务连接时获取的默认环境变量名称、值和配置。

受支持的计算服务

服务连接器可用于将以下计算服务连接到 Azure Database for PostgreSQL:

  • Azure 应用程序服务
  • Azure 容器应用 (Azure Container Apps)
  • Azure Functions(Azure 功能服务)
  • Azure Kubernetes 服务 (AKS)
  • Azure Spring 应用程序

受支持的身份验证类型和客户端类型

下表显示了使用服务连接器将计算服务连接到 Azure Database for PostgreSQL 的身份验证方法和客户端的组合。 “是”表示支持该组合,“否”表示不支持该组合。

客户端类型 系统分配的托管标识 用户分配的托管标识 机密/连接字符串 服务主体
。网
Go (pg)
Java (JDBC)
Java - Spring Boot (JDBC)
Node.js (pg)
PHP (原生)
Python (psycopg2)
Python-Django
Ruby (ruby-pg)

注意

系统分配的托管标识、用户分配的托管标识和服务主体仅在 Azure CLI 上受支持。

默认环境变量名称或应用程序属性和示例代码

根据连接的身份验证类型和客户端类型,参考下表中的连接详细信息和示例代码。 有关命名约定的详细信息,请参阅服务连接器内部一文。

系统分配的托管标识

默认环境变量名称 说明 示例值
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 等客户端库获取托管标识或服务主体的访问令牌。 然后,可使用访问令牌作为密码来连接到数据库。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。

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> 授予权限。 服务连接器设置的连接字符串或配置中的用户名应类似于 aad_<connection name>。 如果使用 Azure 门户,请选择 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

用户分配的托管标识

默认环境变量名称 说明 示例值
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>;

示例代码

请参阅下面的步骤和代码,使用用户分配的托管标识连接到 Azure Database for PostgreSQL。

对于 .NET,没有用于支持无密码连接的插件或库。 可使用 Azure.Identity 等客户端库获取托管标识或服务主体的访问令牌。 然后,可使用访问令牌作为密码来连接到数据库。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。

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> 授予权限。 服务连接器设置的连接字符串或配置中的用户名应类似于 aad_<connection name>。 如果使用 Azure 门户,请选择 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 建议使用最安全的可用身份验证流。 本过程中介绍的身份验证流程需要非常高的信任度,并携带其他流中不存在的风险。 请仅在无法使用其他更安全的流(例如托管标识)时才使用此流。

默认环境变量名称 说明 示例值
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 等客户端库获取托管标识或服务主体的访问令牌。 然后,可使用访问令牌作为密码来连接到数据库。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。

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> 授予权限。 服务连接器设置的连接字符串或配置中的用户名应类似于 aad_<connection name>。 如果使用 Azure 门户,请选择 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

后续步骤

参考下面列出的教程来详细了解服务连接器。