此页面显示了受支持的身份验证方法和客户端,还演示了可用于使用服务连接器将 Azure Database for PostgreSQL 连接到其他云服务的示例代码。 不使用服务连接器,你可能仍然可以使用其他编程语言连接到 Azure Database for PostgreSQL。 此页面还显示了你在创建服务连接时获得的默认环境变量名称和值(或 Spring Boot 配置)。
受支持的计算服务
服务连接器可用于将以下计算服务连接到 Azure Database for PostgreSQL:
- Azure 应用程序服务
- Azure Container Apps
- Azure Functions
- Azure Kubernetes 服务 (AKS)
- Azure Spring Apps
受支持的身份验证类型和客户端类型
下表显示了支持通过身份验证方法和客户端的哪种组合来使用服务连接器将计算服务连接到 Azure Database for PostgreSQL。 “是”表示支持该组合,“否”表示不支持该组合。
客户端类型 |
系统分配的托管标识 |
用户分配的托管标识 |
机密/连接字符串 |
服务主体 |
.NET |
是 |
是 |
是 |
是 |
Go (pg) |
是 |
是 |
是 |
是 |
Java (JDBC) |
是 |
是 |
是 |
是 |
Java - Spring Boot (JDBC) |
是 |
是 |
是 |
是 |
Node.js (pg) |
是 |
是 |
是 |
是 |
PHP (native) |
是 |
是 |
是 |
是 |
Python (psycopg2) |
是 |
是 |
是 |
是 |
Python-Django |
是 |
是 |
是 |
是 |
Ruby (ruby-pg) |
是 |
是 |
是 |
是 |
无 |
是 |
是 |
是 |
是 |
此表支持表中客户端类型和身份验证方法的所有组合都受到支持。 所有客户端类型都可通过服务连接器使用任何身份验证方法连接到 Azure Database for PostgreSQL。
注意
系统分配的托管标识、用户分配的托管标识和服务主体仅在 Azure CLI 上受支持。
默认环境变量名称或应用程序属性和示例代码
根据连接的身份验证类型和客户端类型,参考下表中的连接详细信息和示例代码,将计算服务连接到 Azure Database for PostgreSQL。 有关命名约定的详细信息,请参阅服务连接器内部一文。
系统分配的托管标识
默认环境变量名称 |
说明 |
示例值 |
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_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 连接字符串 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username> |
应用程序属性 |
说明 |
示例值 |
spring.datasource.azure.passwordless-enabled |
启用无密码身份验证 |
true |
spring.datasource.url |
数据库 URL |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
数据库用户名 |
username |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 连接字符串 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_NAME |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP 本机 PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 连接字符串 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
示例代码
请参阅下面的步骤和代码,使用系统分配的托管标识连接到 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();
}
将以下依赖项添加到 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
pip freeze > requirements.txt # Save the dependencies to a file
使用 azure-identity
库获取访问令牌并使用该令牌作为密码。 从服务连接器添加的环境变量中获取连接信息。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# 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)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# 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)
安装依赖项。
pip install azure-identity
使用服务连接器添加的环境变量使用 azure-identity
库获取访问令牌。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
在设置文件中,从服务连接器服务添加的环境变量中获取 Azure PostgreSQL 数据库信息。 使用上一步中获取的 accessToken
来访问数据库。
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
安装依赖项。
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,使用 azidentity
获取访问令牌,然后将它用作密码并使用服务连接器提供的连接信息来连接到 Azure PostgreSQL。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("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.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
安装依赖项。
npm install --save @azure/identity
npm install --save pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 @azure/identity
获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// 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();
})();
对于 PHP,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
在代码中,使用 REST API 使用你喜欢的库获取访问令牌。
对于用户分配的标识和系统分配的标识,应用服务和容器应用提供了一个内部可访问的 REST 终结点,它通过定义两个环境变量(IDENTITY_ENDPOINT
和 IDENTITY_HEADER
)来检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
通过向标识终结点发出 HTTP GET 请求来获取访问令牌,并在查询中将 https://ossrdbms-aad.database.windows.net
用作 resource
。 对于用户分配的标识,请同时在查询中包含服务连接器添加的环境变量中的客户端 ID。
有关服务主体,请参阅 Azure AD 服务到服务访问令牌请求,来查看如何获取访问令牌的详细信息。 发出范围为 https://ossrdbms-aad.database.windows.net/.default
的 POST 请求,并使用服务连接器添加的环境变量中的服务主体的租户 ID、客户端 ID 和客户端密码。
将访问令牌和服务连接器服务添加的环境变量中的 PostgreSQL 连接字符串相结合来建立连接。
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
对于 Ruby,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
安装依赖项。
gem install pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 REST API 获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
应用服务和容器应用提供内部可访问的 REST 终结点用于检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client_id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
若要更详细地了解如何获取服务主体的访问令牌,请参阅 Azure AD 服务到服务访问令牌请求。
接下来,如果你在使用服务连接器之前已经在 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_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 连接字符串 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username> |
应用程序属性 |
说明 |
示例值 |
spring.datasource.azure.passwordless-enabled |
启用无密码身份验证 |
true |
spring.cloud.azure.credential.client-id |
客户端 ID |
<identity-client-ID> |
spring.cloud.azure.credential.client-managed-identity-enabled |
启用户端托管标识 |
true |
spring.datasource.url |
数据库 URL |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
数据库用户名 |
username |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 连接字符串 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_NAME |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<<identity-client-ID>> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP 本机 PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 连接字符串 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
示例代码
请参阅下面的步骤和代码,使用用户分配的托管标识连接到 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();
}
将以下依赖项添加到 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
pip freeze > requirements.txt # Save the dependencies to a file
使用 azure-identity
库获取访问令牌并使用该令牌作为密码。 从服务连接器添加的环境变量中获取连接信息。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# 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)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# 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)
安装依赖项。
pip install azure-identity
使用服务连接器添加的环境变量使用 azure-identity
库获取访问令牌。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
在设置文件中,从服务连接器服务添加的环境变量中获取 Azure PostgreSQL 数据库信息。 使用上一步中获取的 accessToken
来访问数据库。
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
安装依赖项。
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,使用 azidentity
获取访问令牌,然后将它用作密码并使用服务连接器提供的连接信息来连接到 Azure PostgreSQL。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("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.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
安装依赖项。
npm install --save @azure/identity
npm install --save pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 @azure/identity
获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// 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();
})();
对于 PHP,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
在代码中,使用 REST API 使用你喜欢的库获取访问令牌。
对于用户分配的标识和系统分配的标识,应用服务和容器应用提供了一个内部可访问的 REST 终结点,它通过定义两个环境变量(IDENTITY_ENDPOINT
和 IDENTITY_HEADER
)来检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
通过向标识终结点发出 HTTP GET 请求来获取访问令牌,并在查询中将 https://ossrdbms-aad.database.windows.net
用作 resource
。 对于用户分配的标识,请同时在查询中包含服务连接器添加的环境变量中的客户端 ID。
有关服务主体,请参阅 Azure AD 服务到服务访问令牌请求,来查看如何获取访问令牌的详细信息。 发出范围为 https://ossrdbms-aad.database.windows.net/.default
的 POST 请求,并使用服务连接器添加的环境变量中的服务主体的租户 ID、客户端 ID 和客户端密码。
将访问令牌和服务连接器服务添加的环境变量中的 PostgreSQL 连接字符串相结合来建立连接。
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
对于 Ruby,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
安装依赖项。
gem install pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 REST API 获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
应用服务和容器应用提供内部可访问的 REST 终结点用于检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client_id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
若要更详细地了解如何获取服务主体的访问令牌,请参阅 Azure AD 服务到服务访问令牌请求。
接下来,如果你在使用服务连接器之前已经在 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_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 连接字符串 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username>&password=<password> |
应用程序属性 |
说明 |
示例值 |
spring.datasource.url |
数据库 URL |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
数据库用户名 |
<username> |
spring.datasource.password |
数据库密码 |
<password> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 连接字符串 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> password=<password> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_NAME |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_PASSWORD |
数据库密码 |
<database-password> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> password=<password> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_PASSWORD |
数据库密码 |
<password> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP 本机 PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> password=<password> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 连接字符串 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> password=<password> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
AZURE_POSTGRESQL_PASSWORD |
数据库密码 |
<password> |
示例代码
请参阅下面的步骤和代码,使用连接字符串连接到 Azure Database for PostgreSQL。
- 安装依赖项。 按照指南安装 Npgsql
- 在代码中,从服务连接器服务添加的环境变量中获取 PostgreSQL 服务连接器。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
using System;
using Npgsql;
string connectionString = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING");
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
}
- 安装依赖项。 按照指南安装 pgJDBC。
- 在代码中,从服务连接器服务添加的环境变量中获取 PostgreSQL 服务连接器。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
String connectionString = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionString);
System.out.println("Connection successful!");
} catch (SQLException e){
System.out.println(e.getMessage());
}
- 通过将以下依赖项添加到
pom.xml
文件来安装 Spring Cloud Azure Starter JDBC PostgreSQL 模块。 在此处找到 Spring Cloud Azure 的版本。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-dependencies</artifactId>
<version>5.20.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-starter-jdbc-postgresql</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
- 设置 Spring App 应用程序,在此部分了解更多详细信息。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
- 安装依赖项。 按照指南安装 psycopg2。
- 在代码中,从服务连接器服务添加的环境变量中获取 PostgreSQL 连接信息。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
import os
import psycopg2
connection_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
connection = psycopg2.connect(connection_string)
print("Connection established")
connection.close()
- 安装依赖项。 按照指南安装 Django 和 psycopg2。
pip install django
pip install psycopg2
- 在设置文件中,从服务连接器服务添加的环境变量中获取 PostgreSQL 数据库信息。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
# in your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = os.getenv('AZURE_POSTGRESQL_PASSWORD')
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
- 安装依赖项。
go get github.com/lib/pq
- 在代码中,从服务连接器服务添加的环境变量中获取 PostgreSQL 服务连接器。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
import (
"database/sql"
"fmt"
"os"
_ "github.com/lib/pq"
)
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING")
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
- 安装依赖项。
npm install pg dotenv
- 在代码中,从服务连接器服务添加的环境变量中获取 PostgreSQL 连接信息。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
const { Client } = require('pg');
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: process.env.AZURE_POSTGRESQL_PASSWORD,
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();
})();
- 在代码中,从服务连接器服务添加的环境变量中获取 PostgreSQL 连接信息。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
<?php
$conn_string = getenv('AZURE_POSTGRESQL_CONNECTIONSTRING');
$dbconn = pg_connect($conn_string);
?>
- 安装依赖项。
gem install pg
- 在代码中,从服务连接器服务添加的环境变量中获取 PostgreSQL 连接信息。 若要为 PostgreSQL 服务器设置 TSL 配置,请参阅这些步骤。
require 'pg'
require 'dotenv/load'
begin
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'],
)
rescue PG::Error => e
puts e.message
ensure
connection.close if connection
end
服务主体
默认环境变量名称 |
说明 |
示例值 |
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_POSTGRESQL_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 连接字符串 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username> |
应用程序属性 |
说明 |
示例值 |
spring.datasource.azure.passwordless-enabled |
启用无密码身份验证 |
true |
spring.cloud.azure.credential.client-id |
客户端 ID |
<client-ID> |
spring.cloud.azure.credential.client-secret |
客户端密码 |
<client-secret> |
spring.cloud.azure.credential.tenant-id |
租户 ID |
<tenant-ID> |
spring.datasource.url |
数据库 URL |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
数据库用户名 |
username |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 连接字符串 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_NAME |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP 本机 PostgreSQL 连接字符串 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 连接字符串 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
默认环境变量名称 |
说明 |
示例值 |
AZURE_POSTGRESQL_HOST |
数据库主机 URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
数据库用户名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
数据库名称 |
<database-name> |
AZURE_POSTGRESQL_PORT |
端口号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL 选项 |
true |
AZURE_POSTGRESQL_CLIENTID |
客户端 ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
租户 ID |
<tenant-ID> |
示例代码
请参阅下面的步骤和代码,使用服务主体连接到 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();
}
将以下依赖项添加到 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
pip freeze > requirements.txt # Save the dependencies to a file
使用 azure-identity
库获取访问令牌并使用该令牌作为密码。 从服务连接器添加的环境变量中获取连接信息。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# 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)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# 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)
安装依赖项。
pip install azure-identity
使用服务连接器添加的环境变量使用 azure-identity
库获取访问令牌。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
在设置文件中,从服务连接器服务添加的环境变量中获取 Azure PostgreSQL 数据库信息。 使用上一步中获取的 accessToken
来访问数据库。
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
安装依赖项。
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,使用 azidentity
获取访问令牌,然后将它用作密码并使用服务连接器提供的连接信息来连接到 Azure PostgreSQL。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("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.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
安装依赖项。
npm install --save @azure/identity
npm install --save pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 @azure/identity
获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// 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();
})();
对于 PHP,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
在代码中,使用 REST API 使用你喜欢的库获取访问令牌。
对于用户分配的标识和系统分配的标识,应用服务和容器应用提供了一个内部可访问的 REST 终结点,它通过定义两个环境变量(IDENTITY_ENDPOINT
和 IDENTITY_HEADER
)来检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
通过向标识终结点发出 HTTP GET 请求来获取访问令牌,并在查询中将 https://ossrdbms-aad.database.windows.net
用作 resource
。 对于用户分配的标识,请同时在查询中包含服务连接器添加的环境变量中的客户端 ID。
有关服务主体,请参阅 Azure AD 服务到服务访问令牌请求,来查看如何获取访问令牌的详细信息。 发出范围为 https://ossrdbms-aad.database.windows.net/.default
的 POST 请求,并使用服务连接器添加的环境变量中的服务主体的租户 ID、客户端 ID 和客户端密码。
将访问令牌和服务连接器服务添加的环境变量中的 PostgreSQL 连接字符串相结合来建立连接。
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
对于 Ruby,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
安装依赖项。
gem install pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 REST API 获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
应用服务和容器应用提供内部可访问的 REST 终结点用于检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client_id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
若要更详细地了解如何获取服务主体的访问令牌,请参阅 Azure AD 服务到服务访问令牌请求。
接下来,如果你在使用服务连接器之前已经在 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
后续步骤
参考下面列出的教程来详细了解服务连接器。