你可以同時使用系統指派和使用者指派的管理身份,來驗證 適用於 PostgreSQL 的 Azure 資料庫 的彈性伺服器。 本文將教你如何使用系統指派的管理身份來存取 Azure 虛擬機(VM)的 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器。 Azure 會自動管理受管理身份,並讓你能在不需輸入憑證的情況下,驗證支援 Microsoft Entra 認證的服務。
您將學習如何:
- 授權你的虛擬機存取 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器。
- 在資料庫中建立使用者,以代表 VM 系統指派的身分識別。
- 利用虛擬機身份取得存取權杖,並用它查詢 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器。
- 在 C# 範例應用程式中實作權杖擷取。
先決條件
- 如果您不熟悉適用於 Azure 資源的受控識別功能,請參閱此概觀。 如果您沒有 Azure 帳戶,請先 註冊免費帳戶 ,再繼續進行。
- 若要執行所需的資源建立和角色管理,您的帳戶必須在適當的範圍 (您的訂用帳戶或資源群組) 上具備「擁有者」權限。 如果您需要角色指派的協助,則請參閱指派 Azure 角色來管理 Azure 訂用帳戶資源的存取權。
- 你需要一台 Azure 虛擬機(例如運行 Ubuntu Linux)來透過管理身份存取你的資料庫。
- 你需要一台 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器,並且設定了 Microsoft Entra 認證。
- 要遵循 C# 範例,首先完成如何 使用 C# 連接的指南。
為您的 VM 建立系統指派的受控身分識別
使用 az vm identity assign 並搭配 identity assign 指令將系統指派身份加入現有虛擬機:
az vm identity assign -g myResourceGroup -n myVm
為系統指派的受控識別擷取應用程式識別碼,在接下來的幾個步驟中您需要此識別碼:
# Get the client ID (application ID) of the system-assigned managed identity
az ad sp list --display-name vm-name --query [*].appId --out tsv
為您的受控身分識別建立適用於 PostgreSQL 的 Azure 資料庫使用者
現在,以 Microsoft Entra 管理員使用者身份連接到你的 適用於 PostgreSQL 的 Azure 資料庫 靈活伺服器資料庫,並執行以下 SQL 語句。 將 <identity_name> 替換為你為其建立系統指派受控識別的資源名稱。
請注意,pgaadauth_create_principal 必須在 Postgres 資料庫上執行。
select * from pgaadauth_create_principal('<identity_name>', false, false);
成功看起來如下:
pgaadauth_create_principal
-----------------------------------
Created role for "<identity_name>"
(1 row)
如需管理已啟用 Microsoft Entra ID 的資料庫角色的詳細資訊,請參閱 在適用於 PostgreSQL 的 Azure 資料庫中管理 Microsoft Entra 角色。
使用身分識別名稱做為角色名稱並使用 Microsoft Entra 權杖做為密碼進行驗證時,受控身分識別現在會具有存取權。
備註
若管理身份無效,則會回傳錯誤: ERROR: Could not validate AAD user <ObjectId> because its name is not found in the tenant. [...]。
如果您看到「沒有函式符合...」之類的錯誤,請確定您正在連線到 postgres 資料庫,而非您也建立的不同資料庫。
從 Azure 執行個體中繼資料服務擷取存取權杖
您的應用程式現在可以從 Azure 執行個體中繼資料服務擷取存取權杖,並用來向資料庫進行驗證。
藉由對 HTTP 發出 http://169.254.169.254/metadata/identity/oauth2/token 要求並傳遞下列參數來擷取此權杖:
api-version=2018-02-01resource=https://ossrdbms-aad.database.windows.net-
client_id=CLIENT_ID(您稍早已擷取)
您會取回包含 access_token 欄位的 JSON 結果 - 此長文字值是受控身分識別存取權杖,而您應該在連線至資料庫時使用此存取權杖來作為密碼。
針對測試目的,您可以在殼層中執行下列命令。
備註
請注意,您必須安裝 curl、jq 和 psql 用戶端。
# Retrieve the access token
export PGPASSWORD=`curl -s 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fossrdbms-aad.database.windows.net&client_id=CLIENT_ID' -H Metadata:true | jq -r .access_token`
# Connect to the database
psql -h SERVER --user USER DBNAME
您現在已連線至先前設定的資料庫。
使用受控身分識別進行連線
本節說明如何利用虛擬機的使用者指派管理身份取得存取權杖,並用它呼叫 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器。 適用於 PostgreSQL 的 Azure 資料庫原生支援 Microsoft Entra 驗證,因此它可以直接接受使用 Azure 資源受控識別取得的存取權杖。 建立適用於 PostgreSQL 的 Azure 資料庫的連線時,您會在密碼欄位中傳遞存取權杖。
在 Python 中使用受控身分識別進行連線
如需 Python 程式碼範例,請參閱 快速入門:使用 Python 連線和查詢適用於 PostgreSQL 的 Azure 資料庫中的資料
透過使用 Java 中的管理身份來連接
關於 Java 程式碼範例,請參見快速入門:使用 Java 和 JDBC 搭配 適用於 PostgreSQL 的 Azure 資料庫。
透過使用 C 語言中的管理式身份來連接#
這裡有一個 .NET 程式碼範例,透過存取權杖開啟連接 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器的連線。 此程式碼必須在虛擬機上執行,才能使用系統指派的管理身份,從 Microsoft Entra ID 取得存取權杖。 替換 HOST、USER(為 <identity_name>)和 DATABASE 的值。
using Azure.Identity;
using Npgsql;
using System;
class Program
{
static void Main(string[] args)
{
try
{
// Obtain an access token using the system-assigned managed identity
var tokenCredential = new DefaultAzureCredential();
var accessToken = tokenCredential.GetToken(
new Azure.Core.TokenRequestContext(new[] { "https://ossrdbms-aad.database.windows.net/.default" })
);
// Build the connection string
string host = "your-server-name.postgres.database.azure.com"; // Replace with your flexible server's host
string database = "your-database-name"; // Replace with your database name
string user = "<identity_name>"; // Replace with your identity name (e.g., "myManagedIdentity")
var connectionString = $"Host={host};Database={database};Username={user};Password={accessToken.Token};SSL Mode=Require;Trust Server Certificate=true";
// Open a connection to the database
using var connection = new NpgsqlConnection(connectionString);
connection.Open();
Console.WriteLine("Connection successful!");
// Optional: Perform a simple query
using var command = new NpgsqlCommand("SELECT version();", connection);
using var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"PostgreSQL version: {reader.GetString(0)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
請填寫以下佔位符:
-
HOST:替換your-server-name.postgres.database.azure.com成你伺服器的主機名稱。 -
USER:替換<identity_name>成你的管理身份名稱。 -
DATABASE:請將your-database-name替換為您的 適用於 PostgreSQL 的 Azure 資料庫 彈性伺服器名稱。 - Microsoft Entra 驗證:程式碼會使用 VM 的系統指派受控識別,從 Microsoft Entra ID 擷取存取權杖。
執行這個指令時,你會得到如下的輸出:
Getting access token from Azure AD...
Opening connection using access token...
Connected!
Postgres version: PostgreSQL 11.11, compiled by Visual C++ build 1800, 64-bit