本文涵蓋支持的驗證方法、用戶端和範例程序代碼,您可以使用 Service Connector 將應用程式連線至適用於 PostgreSQL 的 Azure 資料庫。 在本文中,您也會找到建立服務連線時取得的默認環境變數名稱、值和組態。
支援的計算服務
服務連接器可用來將下列計算服務連線至適用於 PostgreSQL 的 Azure 資料庫:
- Azure App Service
- Azure 容器應用程式
- Azure Functions(Microsoft 雲端服務)
- Azure Kubernetes Service (AKS)
- Azure Spring 應用程式
支援的驗證類型和用戶端類型
下表顯示使用服務連接器將計算服務連線到適用於 PostgreSQL 的 Azure 資料庫時,支援驗證方法和客戶端的組合。 「是」表示支援的組合,而「否」則表示不支援。
用戶端類型 |
系統指派的受控識別 |
使用者指派的受控識別 |
祕密/連接字串 |
服務主體 |
。NET |
是的 |
是的 |
是的 |
是的 |
圍棋(頁) |
是的 |
是的 |
是的 |
是的 |
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_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 |
範例指令碼
請參閱下列步驟和程式碼,以使用系統指派的受控識別來連線到適用於 PostgreSQL 的 Azure 資料庫。
在 .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
在程式碼中,從服務連接器服務新增的環境變數中,使用 @azure/identity
和 PostgreSQL 連線資訊來取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
import { Client } from '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 搭配您慣用的程式庫來取得存取權杖。
針對使用者指派的身分識別和系統指派的身分識別,App Service 和容器應用程式提供可從內部存取的 REST 端點來擷取受控識別的權杖,方法是定義兩個環境變數:IDENTITY_ENDPOINT
和 IDENTITY_HEADER
。 如需詳細資訊,請參閱 REST 端點參考 (部分機器翻譯)。
對身分識別端點提出 HTTP GET 要求,並在查詢中使用 https://ossrdbms-aad.database.windows.net
作為 resource
,來取得存取權杖。 針對使用者指派的身分識別,請同時在查詢中包括服務連接器新增之環境變數的用戶端識別碼。
針對服務主體,請參閱 Azure AD 服務對服務存取權杖要求以查看如何取得存取權杖的詳細資料。 將 POST 要求的範圍設定為 https://ossrdbms-aad.database.windows.net/.default
,並搭配服務連接器新增之環境變數中的服務主體租用戶識別碼、用戶端識別碼和用戶端密碼。
結合由 Service Connector 服務提供的環境變數中的存取令牌與 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
在程式碼中,使用 REST API 和從服務連接器服務新增的環境變數中的 PostgreSQL 連線資訊來取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
App Service 和容器應用程式提供可從內部存取的 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 彈性伺服器中建立資料表和序列,則必須以擁有者身分連線,並將權限授與 Service Connector 所建立的 <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 |
您的用戶端識別碼 |
<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 |
您的用戶端識別碼 |
<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 |
您的用戶端識別碼 |
<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 |
您的用戶端識別碼 |
<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 |
您的用戶端識別碼 |
<<identity-client-ID>> |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_POSTGRESQL_CLIENTID |
您的用戶端識別碼 |
<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 |
您的用戶端識別碼 |
<identity-client-ID> |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_POSTGRESQL_CLIENTID |
您的用戶端識別碼 |
<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 |
您的用戶端識別碼 |
<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 |
您的用戶端識別碼 |
<identity-client-ID> |
範例指令碼
請參閱下列步驟和程式碼,以使用使用者指派的受控識別來連線到適用於 PostgreSQL 的 Azure 資料庫。
在 .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
在程式碼中,從服務連接器服務新增的環境變數中,使用 @azure/identity
和 PostgreSQL 連線資訊來取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
import { Client } from '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 搭配您慣用的程式庫來取得存取權杖。
針對使用者指派的身分識別和系統指派的身分識別,App Service 和容器應用程式提供可從內部存取的 REST 端點來擷取受控識別的權杖,方法是定義兩個環境變數:IDENTITY_ENDPOINT
和 IDENTITY_HEADER
。 如需詳細資訊,請參閱 REST 端點參考 (部分機器翻譯)。
對身分識別端點提出 HTTP GET 要求,並在查詢中使用 https://ossrdbms-aad.database.windows.net
作為 resource
,來取得存取權杖。 針對使用者指派的身分識別,請同時在查詢中包括服務連接器新增之環境變數的用戶端識別碼。
針對服務主體,請參閱 Azure AD 服務對服務存取權杖要求以查看如何取得存取權杖的詳細資料。 將 POST 要求的範圍設定為 https://ossrdbms-aad.database.windows.net/.default
,並搭配服務連接器新增之環境變數中的服務主體租用戶識別碼、用戶端識別碼和用戶端密碼。
結合由 Service Connector 服務提供的環境變數中的存取令牌與 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
在程式碼中,使用 REST API 和從服務連接器服務新增的環境變數中的 PostgreSQL 連線資訊來取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
App Service 和容器應用程式提供可從內部存取的 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 彈性伺服器中建立資料表和序列,則必須以擁有者身分連線,並將權限授與 Service Connector 所建立的 <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> |
範例指令碼
請參閱下列步驟和程式碼,以使用連接字串來連線到適用於 PostgreSQL 的 Azure 資料庫。
- 請按照 Npgsql 指引 安裝相依性
- 在程序代碼中,從 Service Connector 新增的環境變數取得 PostgreSQL 連接字串。
using System;
using Npgsql;
string connectionString = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING");
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
}
- 遵循 pgJDBC 指引安裝相依套件。
- 在程序代碼中,從 Service Connector 新增的環境變數取得 PostgreSQL 連接字串。
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 Boot 應用程式,本節中的詳細資訊。
- 請依照 psycopg2 指引安裝相依套件。
- 在程序代碼中,從 Service Connector 新增的環境變數取得 PostgreSQL 連線資訊。
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
- 在設定檔中,從 Service Connector 新增的環境變數取得 PostgreSQL 資料庫資訊。
# 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
- 在程序代碼中,從 Service Connector 新增的環境變數取得 PostgreSQL 連接字串。
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
- 在程序代碼中,從 Service Connector 新增的環境變數取得 PostgreSQL 連線資訊。
import { Client } from '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();
})();
- 在程序代碼中,從 Service Connector 新增的環境變數取得 PostgreSQL 連線資訊。
<?php
$conn_string = getenv('AZURE_POSTGRESQL_CONNECTIONSTRING');
$dbconn = pg_connect($conn_string);
?>
- 安裝相依性。
gem install pg
- 在程序代碼中,從 Service Connector 新增的環境變數取得 PostgreSQL 連線資訊。
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 |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<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 |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<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 |
您的用戶端識別碼 |
<client-ID> |
spring.cloud.azure.credential.client-secret |
您的用戶端密碼 |
<client-secret> |
spring.cloud.azure.credential.tenant-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 |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<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 |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<tenant-ID> |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_POSTGRESQL_CLIENTID |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<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 |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<tenant-ID> |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_POSTGRESQL_CLIENTID |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<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 |
您的用戶端識別碼 |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<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 |
您的用戶端識別碼 |
<identity-client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
您的用戶端密碼 |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
您的租用戶識別碼 |
<tenant-ID> |
範例指令碼
請參閱下列步驟和程式碼,以使用服務主體來連線到適用於 PostgreSQL 的 Azure 資料庫。
在 .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
在程式碼中,從服務連接器服務新增的環境變數中,使用 @azure/identity
和 PostgreSQL 連線資訊來取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
import { Client } from '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 搭配您慣用的程式庫來取得存取權杖。
針對使用者指派的身分識別和系統指派的身分識別,App Service 和容器應用程式提供可從內部存取的 REST 端點來擷取受控識別的權杖,方法是定義兩個環境變數:IDENTITY_ENDPOINT
和 IDENTITY_HEADER
。 如需詳細資訊,請參閱 REST 端點參考 (部分機器翻譯)。
對身分識別端點提出 HTTP GET 要求,並在查詢中使用 https://ossrdbms-aad.database.windows.net
作為 resource
,來取得存取權杖。 針對使用者指派的身分識別,請同時在查詢中包括服務連接器新增之環境變數的用戶端識別碼。
針對服務主體,請參閱 Azure AD 服務對服務存取權杖要求以查看如何取得存取權杖的詳細資料。 將 POST 要求的範圍設定為 https://ossrdbms-aad.database.windows.net/.default
,並搭配服務連接器新增之環境變數中的服務主體租用戶識別碼、用戶端識別碼和用戶端密碼。
結合由 Service Connector 服務提供的環境變數中的存取令牌與 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
在程式碼中,使用 REST API 和從服務連接器服務新增的環境變數中的 PostgreSQL 連線資訊來取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
App Service 和容器應用程式提供可從內部存取的 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 彈性伺服器中建立資料表和序列,則必須以擁有者身分連線,並將權限授與 Service Connector 所建立的 <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
下一步
請遵循下方列出的教學課程以深入了解服務連接器。