Share via


教學課程:透過 Service 連線 or 建立資料庫服務的無密碼連線

無密碼聯機會使用受控識別來存取 Azure 服務。 使用這種方法,您不需要手動追蹤和管理受控識別的秘密。 Azure 會在內部安全地處理這些工作。

服務 連線 or 可在 Azure Spring Apps、Azure App 服務 和 Azure Container Apps 等應用程式裝載服務中啟用受控識別。 服務 連線 or 也會設定資料庫服務,例如 適用於 PostgreSQL 的 Azure 資料庫、適用於 MySQL 的 Azure 資料庫 和 Azure SQL 資料庫,以接受受控識別。

在本教學課程中,您會使用 Azure CLI 來完成下列工作:

  • 使用 Azure CLI 檢查您的初始環境。
  • 使用 Service 連線 or 建立無密碼連線。
  • 使用 Service 連線 or 所產生的環境變數或組態來存取資料庫服務。

必要條件

設定您的環境

客戶​​

透過 az login使用 Azure CLI 登入。 如果您使用 Azure Cloud Shell 或已登入,請使用 確認已驗證的帳戶 az account show

安裝服務 連線 或無密碼擴充功能

安裝 Azure CLI 的服務 連線 或無密碼擴充功能:

az extension add --name serviceconnector-passwordless --upgrade

建立無密碼連線

接下來,我們會使用 Azure App 服務 作為範例,以使用受控識別建立連線。

如果您使用:

注意

如果您使用 Azure 入口網站,請移至 Azure App 服務、Azure Spring Apps 或 Azure Container Apps 的服務 連線 or 刀鋒視窗,然後選取 [建立] 以建立連線。 Azure 入口網站 會自動為您撰寫命令,並在 Cloud Shell 上觸發命令執行。

下列 Azure CLI 命令會使用 --client-type 參數。 az webapp connection create postgres-flexible -h執行 以取得支援的用戶端類型,然後選擇符合您應用程式的客戶端類型。

az webapp connection create postgres-flexible \
    --resource-group $RESOURCE_GROUP \
    --name $APPSERVICE_NAME \
    --target-resource-group $RESOURCE_GROUP \
    --server $POSTGRESQL_HOST \
    --database $DATABASE_NAME \
    --user-identity client-id=XX subs-id=XX \
    --client-type java

適用於 MySQL 的 Azure 資料庫 - 彈性伺服器需要使用者指派的受控識別,才能啟用 Microsoft Entra 驗證。 如需詳細資訊,請參閱為 適用於 MySQL 的 Azure 資料庫 - 彈性伺服器設定 Microsoft Entra 驗證。 您可以使用下列命令來建立使用者指派的受控識別:

USER_IDENTITY_NAME=<YOUR_USER_ASSIGNED_MANAGEMED_IDENTITY_NAME>
IDENTITY_RESOURCE_ID=$(az identity create \
    --name $USER_IDENTITY_NAME \
    --resource-group $RESOURCE_GROUP \
    --query id \
    --output tsv)

重要

建立使用者指派的受控識別之後,請要求全域 管理員 istrator 或 Privileged Role 管理員 istrator 授與此身分識別的下列許可權:

  • User.Read.All
  • GroupMember.Read.All
  • Application.Read.All

如需詳細資訊,請參閱 Active Directory 驗證的許可權一節。

然後,使用服務 連線 or,將您的應用程式連線到具有系統指派受控識別的 MySQL 資料庫。

下列 Azure CLI 命令會使用 --client-type 參數。 az webapp connection create mysql-flexible -h執行 以取得支援的用戶端類型,然後選擇符合您應用程式的客戶端類型。

az webapp connection create mysql-flexible \
    --resource-group $RESOURCE_GROUP \
    --name $APPSERVICE_NAME \
    --target-resource-group $RESOURCE_GROUP \
    --server $MYSQL_HOST \
    --database $DATABASE_NAME \
    --user-identity client-id=XX subs-id=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
    --client-type java

下列 Azure CLI 命令會使用 --client-type 參數。 az webapp connection create sql -h執行 以取得支援的用戶端類型,然後選擇符合您應用程式的客戶端類型。

az webapp connection create sql \
    --resource-group $RESOURCE_GROUP \
    --name $APPSERVICE_NAME \
    --target-resource-group $RESOURCE_GROUP \
    --server $SQL_HOST \
    --database $DATABASE_NAME \
    --user-identity client-id=XX subs-id=XX \
    --client-type dotnet

此服務 連線 or 命令會在背景中完成下列工作:

  • 啟用系統指派的受控識別,或為 Azure App 服務/Azure Spring Apps/Azure Container Apps 所裝載的應用程式$APPSERVICE_NAME指派使用者身分識別。
  • 將 Microsoft Entra 系統管理員設定為目前的登入使用者。
  • 為系統指派的受控識別、使用者指派的受控識別或服務主體新增資料庫使用者。 將資料庫 $DATABASE_NAME 的所有許可權授與此使用者。 您可以在上述命令輸出中的 連接字串 中找到使用者名稱。
  • 根據資料庫類型,將名為 AZURE_MYSQL_CONNECTIONSTRINGAZURE_POSTGRESQL_CONNECTIONSTRINGAZURE_SQL_CONNECTIONSTRING 的組態設定為 Azure 資源。
    • 針對 App Service,設定會在 [應用程式 設定] 刀鋒視窗中設定
    • 針對 Spring Apps,會在啟動應用程式時設定組態。
    • 針對 Container Apps,組態會設定為環境變數。 您可以在 Azure 入口網站 的 [服務 連線 or] 刀鋒視窗中取得所有設定及其值。

使用 Microsoft Entra 驗證 連線 至資料庫

建立連線之後,您可以使用應用程式中的 連接字串,使用 Microsoft Entra 驗證連線到資料庫。 例如,您可以使用下列解決方案,透過 Microsoft Entra 驗證連線到資料庫。

針對 .NET,沒有外掛程式或連結庫可支持無密碼連線。 您可以使用 Azure.Identity 之類的客戶端連結庫,取得受控識別或服務主體的存取令牌。 然後,您可以使用存取令牌作為密碼來連線到資料庫。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。

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

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

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

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

// Acquire the access token. 
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
    new TokenRequestContext(scopes: new string[]
    {
        "https://ossrdbms-aad.database.windows.net/.default"
    }));

// Combine the token with the connection string from the environment variables provided by Service Connector.
string connectionString =
    $"{Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING")};Password={accessToken.Token}";

// Establish the connection.
using (var connection = new NpgsqlConnection(connectionString))
{
    Console.WriteLine("Opening connection using access token...");
    connection.Open();
}

接下來,如果您已在 PostgreSQL 彈性伺服器中建立數據表和序列,再使用 Service 連線 or,您必須連線為擁有者,並授與 Service 連線 or 所建立的許可權<aad-username>。 Service 連線 or 所設定之 連接字串 或組態的使用者名稱看起來應該像 aad_<connection name>。 如果您使用 Azure 入口網站,請選取數據行旁邊的Service Type展開按鈕並取得值。 如果您使用 Azure CLI,請檢查 configurations CLI 命令輸出。

然後,執行查詢以授與許可權

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>是 Service 連線 or 所建立的使用者。 以實際值取代它們。

使用 命令驗證結果:

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

針對 .NET,沒有外掛程式或連結庫可支持無密碼連線。 您可以使用 Azure.Identity 之類的客戶端連結庫,取得受控識別或服務主體的存取令牌。 然後,您可以使用存取令牌作為密碼來連線到資料庫。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。

using Azure.Core;
using Azure.Identity;
using MySqlConnector;

// Uncomment the following lines according to the authentication type.
// For system-assigned managed identity.
// var credential = new DefaultAzureCredential();

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

// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_MYSQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTSECRET");
// var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

var tokenRequestContext = new TokenRequestContext(
    new[] { "https://ossrdbms-aad.database.windows.net/.default" });
AccessToken accessToken = await credential.GetTokenAsync(tokenRequestContext);
// Open a connection to the MySQL server using the access token.
string connectionString =
    $"{Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING")};Password={accessToken.Token}";

using var connection = new MySqlConnection(connectionString);
Console.WriteLine("Opening connection using access token...");
await connection.OpenAsync();

// do something

如需更多程式代碼範例,請參閱使用受控識別從 App Service 連線 至 Azure 資料庫,而不使用秘密。

  1. 安裝相依性。

    dotnet add package Microsoft.Data.SqlClient
    
  2. 從 Service 連線 or 所新增的環境變數取得 Azure SQL 資料庫 連接字串。

    using Microsoft.Data.SqlClient;
    
    string connectionString = 
        Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
    
    using var connection = new SqlConnection(connectionString);
    connection.Open();
    

    如需詳細資訊,請參閱 使用 Active Directory 受控識別驗證

如需詳細資訊,請參閱 Microsoft SQL Server 用戶端程式設計首頁。

將應用程式部署至 Azure 主控服務

最後,將您的應用程式部署至 Azure 主控服務。 該來源服務可以使用受控識別來連線到 Azure 上的目標資料庫。

針對 Azure App 服務,您可以透過 az webapp deploy 命令部署應用程式程式代碼。 如需詳細資訊,請參閱 快速入門:部署 ASP.NET Web 應用程式

然後,您可以檢查記錄檔或呼叫應用程式,以查看是否可以成功連線到 Azure 資料庫。

疑難排解

權限

如果您遇到任何許可權相關錯誤,請使用 命令 az account show確認 Azure CLI 登入的使用者。 請確定您已使用正確的帳戶登入。 接下來,請確認您具有下列許可權,可能需要建立與 Service 連線 or 的無密碼連線。

權限 作業
Microsoft.DBforPostgreSQL/flexibleServers/read 取得資料庫伺服器資訊的必要專案
Microsoft.DBforPostgreSQL/flexibleServers/write 啟用資料庫伺服器的 Microsoft Entra 驗證的必要專案
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/write 如果本機 IP 位址遭到封鎖,則需要建立防火牆規則
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/delete 需要還原 Service 連線 or 所建立的防火牆規則,以避免安全性問題
Microsoft.DBforPostgreSQL/flexibleServers/administrators/read 需要檢查 Azure CLI 登入使用者是否為資料庫伺服器 Microsoft Entra 系統管理員
Microsoft.DBforPostgreSQL/flexibleServers/administrators/write 將 Azure CLI 登入使用者新增為資料庫伺服器 Microsoft Entra 系統管理員的必要專案
權限 作業
Microsoft.DBforMySQL/flexibleServers/read 取得資料庫伺服器資訊的必要專案
Microsoft.DBforMySQL/flexibleServers/write 將所提供的使用者指派受控識別新增至資料庫伺服器的必要專案
Microsoft.DBforMySQL/flexibleServers/firewallRules/write 如果本機 IP 位址遭到封鎖,則需要建立防火牆規則
Microsoft.DBforMySQL/flexibleServers/firewallRules/delete 需要還原 Service 連線 or 所建立的防火牆規則,以避免安全性問題
Microsoft.DBforMySQL/flexibleServers/administrators/read 需要檢查 Azure CLI 登入使用者是否為資料庫伺服器 Microsoft Entra 系統管理員
Microsoft.DBforMySQL/flexibleServers/administrators/write 將 Azure CLI 登入使用者新增為資料庫伺服器 Microsoft Entra 系統管理員的必要專案
權限 作業
Microsoft.Sql/servers/read 取得資料庫伺服器資訊的必要專案
Microsoft.Sql/servers/firewallRules/write 如果本機 IP 位址遭到封鎖,則需要建立防火牆規則
Microsoft.Sql/servers/firewallRules/delete 需要還原 Service 連線 or 所建立的防火牆規則,以避免安全性問題
Microsoft.Sql/servers/administrators/read 需要檢查 Azure CLI 登入使用者是否為資料庫伺服器 Microsoft Entra 系統管理員
Microsoft.Sql/servers/administrators/write 將 Azure CLI 登入使用者新增為資料庫伺服器 Microsoft Entra 系統管理員的必要專案

在某些情況下,不需要許可權。 例如,如果 Azure CLI 驗證的用戶已經是 SQL Server 上的 Active Directory 管理員 istrator,您就不需要擁有 Microsoft.Sql/servers/administrators/write 許可權。

Microsoft Entra ID

如果您收到錯誤 ERROR: AADSTS530003: Your device is required to be managed to access this resource.,請要求IT部門協助將此裝置加入 Microsoft Entra ID。 如需詳細資訊,請參閱 已加入 Microsoft Entra 的裝置

服務 連線 or 必須存取 Microsoft Entra ID,才能取得您的帳戶和裝載服務的受控識別資訊。 您可以使用下列命令來檢查您的裝置是否可以存取 Microsoft Entra ID:

az ad signed-in-user show

如果您未以互動方式登入,也可能會收到錯誤 和 Interactive authentication is needed。 若要解決錯誤,請使用 az login 命令登入。

網路連線

如果您的資料庫伺服器位於 虛擬網絡 中,請確定執行 Azure CLI 命令的環境可以存取 虛擬網絡 中的伺服器。

如果您的資料庫伺服器位於 虛擬網絡,請確定執行 Azure CLI 命令的環境可以存取 虛擬網絡 中的伺服器。

如果您的資料庫伺服器不允許公用存取,請確定執行 Azure CLI 命令的環境可以透過私人端點存取伺服器。

下一步

如需服務 連線 或無密碼連線的詳細資訊,請參閱下列資源: