共用方式為


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

無密碼連線會使用受控識別來存取 Azure 服務。 藉由此方法,您無須手動追蹤和管理受控識別的秘密。 Azure 會在內部妥善處理這些工作。

服務連接器可在多種應用程式裝載服務中啟用受控識別,例如 Azure Spring 應用程式、Azure App Service 和 Azure 容器應用程式。 Service Connector 也會在 Microsoft Fabric 中設定資料庫服務,例如適用於 PostgreSQL 的 Azure 資料庫、適用於 MySQL 的 Azure 資料庫、Azure SQL Database 和 SQL 資料庫,以接受受控識別。

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

  • 使用 Azure CLI 檢查您的初始環境。
  • 使用服務連接器建立無密碼連線。
  • 使用服務連接器產生的環境變數或設定來存取資料庫服務。

先決條件

若要開始使用 Azure CLI:

安裝服務連接器 無密碼延伸模組

安裝 Azure CLI 的最新服務連接器無密碼延伸模組:

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

附註

請執行 az version 來檢查延伸模組 "serviceconnector-passwordless" 版本為 "2.0.2" 或更高版本。 您可能需要先升級 Azure CLI,才能升級延伸模組版本。

建立無密碼連線

接著,我們會使用 Azure App Service 作為範例,使用受控識別建立連線。

如果您使用:

附註

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

下列 Azure CLI 命令會使用 --client-type 參數,可以是 java、dotnet、python 等等。執行 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 $CLIENT_TYPE

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

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

重要事項

建立使用者指派的受控識別後,請要求全域管理員或特殊權限角色管理員授與此身分識別的下列權限:

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

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

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

使用 --client-type 參數執行下列 Azure CLI 命令。 執行 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

使用 --client-type 參數執行下列 Azure CLI 命令。 執行 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

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

重要事項

目前需要手動存取共用才能完成上線。 請參閱 Fabric 中 SQL 資料庫的存取權共用

az webapp connection create fabricsql \
    --resource-group $RESOURCE_GROUP \
    --name $APPSERVICE_NAME \
    --fabric-workspace-uuid $FABRIC_WORKSPACE_UUID \
    --fabric-sql-db-uuid $FABRIC_SQL_DB_UUID \
    --user-identity client-id=XX subs-id=XX \
    --client-type dotnet

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

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

服務連接器會將下列權限指派給使用者,您可以撤銷這些權限,以及根據自身需求調整權限。

GRANT ALL PRIVILEGES ON DATABASE "$DATABASE_NAME" TO "username"; 

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "username"; 

GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO "username"; 

GRANT ALL PRIVILEGES ON $DATABASE_NAME.* TO 'username'@'%'; 
GRANT CONTROL ON DATABASE::"$DATABASE_NAME" TO "username";
ALTER ROLE db_datareader ADD MEMBER "username"
ALTER ROLE db_datawriter ADD MEMBER "username"
ALTER ROLE db_ddladmin ADD MEMBER "username"

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

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

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

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

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

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

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

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

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

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

接下來,如果您在使用服務連接器之前已在 PostgreSQL 彈性伺服器中建立資料表和序列,則必須以擁有者身分連線,並將權限授與 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

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

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

// Uncomment the following lines corresponding to the authentication type you want to use.
// 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. 從服務連接器新增的環境變數取得 Azure SQL Database 連結字串。

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

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

如需更多資訊,請參閱 Microsoft SQL Server 用戶端程式開發資源頁面

  1. 安裝相依性。

    dotnet add package Microsoft.Data.SqlClient
    
  2. 從 Service Connector 新增的環境變數擷取 Microsoft Fabric 連接字串中的 SQL 資料庫。

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

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

如需詳細資訊,請參閱 在 Microsoft Fabric 中聯機到 SQL 資料庫

將應用程式部署至 Azure 裝載服務

  1. 將您的應用程式部署至 Azure 主控服務。 如需部署這些資源的詳細資訊,請選擇性地參閱下列指南。

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

疑難排解

權限

如果遇到任何權限相關錯誤,請使用命令 az account show 確認 Azure CLI 登入使用者。 請確定您使用正確的帳戶登入。 接著,請確認您具有下列在使用服務連接器建立無密碼連線時可能需要的權限。

權限 作業
Microsoft.DBforPostgreSQL/flexibleServers/read 取得資料庫伺服器的資訊時須具備
Microsoft.DBforPostgreSQL/flexibleServers/write 為資料庫伺服器啟用 Microsoft Entra 驗證時須具備
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/write 在本機 IP 位址遭到封鎖的情況下建立防火牆規則時須具備
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/delete 在還原服務連接器建立的防火牆規則以避免安全性問題時須具備
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 在還原服務連接器建立的防火牆規則以避免安全性問題時須具備
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 在還原服務連接器建立的防火牆規則以避免安全性問題時須具備
Microsoft.Sql/servers/administrators/read 在檢查 Azure CLI 登入使用者是否為資料庫伺服器 Microsoft Entra 系統管理員時須具備
Microsoft.Sql/servers/administrators/write 將 Azure CLI 登入使用者新增為資料庫伺服器 Microsoft Entra 系統管理員時須具備

在某些情況下不需要這些權限。 例如,如果 Azure CLI 驗證的使用者已是 SQL 伺服器的 Active Directory 系統管理員,您就不需要具備 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 的裝置

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

az ad signed-in-user show

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

網路連線

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

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

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

後續步驟

如需 Service Connector 和無密碼連線的詳細資訊,請參閱下列資源: