App Service 可在 Azure 中提供可高度擴充、自我修復的 Web 主控服務。 此服務也為您的應用程式提供受控識別,這是用於保護下列 Azure 資料庫存取權的周全解決方案:
App Service 中的受控識別可藉由從應用程式刪除祕密 (例如連接字串中的認證),讓應用程式更加安全。 本教學課程說明如何使用受控識別,從 App Service 連線到上述資料庫。
您將了解:
- 將 Microsoft Entra 使用者設定為 Azure 資料庫的系統管理員。
- 以 Microsoft Entra 使用者身分連線到您的資料庫。
- 為 App Service 應用程式設定系統指派或使用者指派的受控識別。
- 將資料庫存取權授與受控識別。
- 使用受控識別,透過程式碼 (.NET Framework 4.8、.NET 6、Node.js、Python、Java) 連線到 Azure 資料庫。
- 使用 Microsoft Entra 使用者,透過開發環境連線到 Azure 資料庫。
如果您沒有 Azure 帳戶,請在開始之前建立 免費帳戶 。
必要條件
- 在 App Service 中建立以 .NET、Node.js、Python 或 Java 為基礎的應用程式。
- 使用 Azure SQL Database、適用於 MySQL 的 Azure 資料庫或適用於 PostgreSQL 的 Azure 資料庫,建立資料庫伺服器。
- 您應該熟悉標準連線模式 (透過使用者名稱和密碼),並能夠成功從您的 App Service 應用程式連線到所選資料庫。
備妥環境以使用 Azure CLI。
1.安裝服務連接器 無密碼擴充功能
安裝 Azure CLI 的最新服務連接器無密碼延伸模組:
az extension add --name serviceconnector-passwordless --upgrade
注意
請執行 az version 來檢查延伸模組 "serviceconnector-passwordless" 版本為 "2.0.2" 或更高版本。 您可能需要先升級 Azure CLI,才能升級延伸模組版本。
2.建立無密碼連線
接下來,使用服務連接器建立無密碼連線。
提示
Azure 入口網站可協助您撰寫下列命令。 在 Azure 入口網站中,前往 Azure App Service 資源,從左側功能表中選取 [服務連接器],然後選取 [建立]。 在表單中填寫所有必要參數。 Azure 會自動產生連線建立命令,您可以在 CLI 中複製該命令,或在 Azure Cloud Shell 中執行。
使用 --client-type 參數執行下列 Azure CLI 命令。
選擇性地執行 az webapp connection create sql -h 以取得支援的客戶端類型。
選擇客戶端類型並執行對應的命令。 請將下列預留位置取代為您自己的資訊。
az webapp connection create sql \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <sql-group-name> \
--server <sql-name> \
--database <database-name> \
--user-identity client-id=<client-id> subs-id=<subscription-id> \
--client-type <client-type>
az webapp connection create sql \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <sql-name> \
--database <database-name> \
--system-identity \
--client-type <client-type>
注意
針對適用於 MySQL 的 Azure 資料庫 - 彈性伺服器,您必須先手動設定 Microsoft Entra 驗證,這需要個別使用者指派的受控識別和特定的 Microsoft Graph 權限。 此步驟無法自動化。
為適用於 MySQL 的 Azure 資料庫彈性伺服器手動設定 Microsoft Entra 驗證。
選擇性地執行命令 az webapp connection create mysql-flexible -h 以取得支援的客戶端類型。
選擇客戶端類型並執行對應的命令。 使用 --client-type 參數執行下列 Azure CLI 命令。
az webapp connection create mysql-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <mysql-name> \
--database <database-name> \
--user-identity client-id=XX subs-id=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type <client-type>
az webapp connection create mysql-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <mysql-name> \
--database <database-name> \
--system-identity mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type <client-type>
使用 --client-type 參數執行下列 Azure CLI 命令。
選擇性地執行命令 az webapp connection create postgres-flexible -h 以取得所有支援的客戶端類型清單。
選擇客戶端類型並執行對應的命令。
az webapp connection create postgres-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <postgresql-name> \
--database <database-name> \
--user-identity client-id=XX subs-id=XX \
--client-type java
az webapp connection create postgres-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <postgresql-name> \
--database <database-name> \
--system-identity \
--client-type <client-type>
授與預先建立資料表的權限
接下來,如果您在使用服務連接器之前已在 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 App Service 所裝載的應用程式
<server-name> 指派使用者身分識別。
- 將 Microsoft Entra 系統管理員設定為目前的登入使用者。
- 為系統指派的受控識別或使用者指派的受控識別新增資料庫使用者。 將資料庫的所有權限
<database-name> 授與此使用者。 您可以在上述指令輸出中的連接字串中找到使用者名稱。
- 根據資料庫類型,將名為
AZURE_MYSQL_CONNECTIONSTRING、AZURE_POSTGRESQL_CONNECTIONSTRING或 AZURE_SQL_CONNECTIONSTRING 的組態設定為 Azure 資源。
- 針對 App Service,組態會在 [應用程式設定] 刀鋒視窗中設定。
如果您在建立連線時遇到任何問題,請參閱疑難排解以取得協助。
3.修改您的程式碼
安裝相依性。
dotnet add package Microsoft.Data.SqlClient
從服務連接器新增的環境變數取得 Azure SQL Database 連結字串。
using Microsoft.Data.SqlClient;
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity:"Server=tcp:<server-name>.database.windows.net;Database=<database-name>;Authentication=Active Directory Default;TrustServerCertificate=True"
// For user-assigned managed identity: "Server=tcp:<server-name>.database.windows.net;Database=<database-name>;Authentication=Active Directory Default;User Id=<client-id-of-user-assigned-identity>;TrustServerCertificate=True"
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
如需詳細資訊,請參閱使用 Active Directory 受控識別驗證。
在您的 pom.xml 中新增下列相依性:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
從服務連接器新增的環境變數取得 Azure SQL Database 連結字串。
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class Main {
public static void main(String[] args) {
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};msiClientId={UserAssignedMiClientId};authentication=ActiveDirectoryMSI;"
String connectionString = System.getenv("AZURE_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
如需詳細資訊,請參閱使用 Microsoft Entra 驗證連結。
安裝相依性。
python -m pip install pyodbc
從服務連接器新增的環境變數取得 Azure SQL Database 連結組態。 取消註解您要使用的驗證類型的程式碼片段部分。
import os;
import pyodbc
server = os.getenv('AZURE_SQL_SERVER')
port = os.getenv('AZURE_SQL_PORT')
database = os.getenv('AZURE_SQL_DATABASE')
authentication = os.getenv('AZURE_SQL_AUTHENTICATION') # The value should be 'ActiveDirectoryMsi'
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity.
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server={server},{port};Database={database};Authentication={authentication};Encrypt=yes;'
# For user-assigned managed identity.
# client_id = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server={server},{port};Database={database};UID={client_id};Authentication={authentication};Encrypt=yes;'
conn = pyodbc.connect(connString)
如需替代方法,您也可以使用存取權杖連線到 Azure SQL Database,請參閱移轉 Python 應用程式以使用無密碼連線搭配 Azure SQL Database。
- 安裝相依性。
npm install mssql
- 從服務連接器新增的環境變數取得 Azure SQL Database 連結設定。 取消註解您要使用的驗證類型的程式碼片段部分。
import sql from 'mssql';
const server = process.env.AZURE_SQL_SERVER;
const database = process.env.AZURE_SQL_DATABASE;
const port = parseInt(process.env.AZURE_SQL_PORT);
const authenticationType = process.env.AZURE_SQL_AUTHENTICATIONTYPE;
// Uncomment the following lines according to the authentication type.
// For system-assigned managed identity.
// const config = {
// server,
// port,
// database,
// authentication: {
// authenticationType
// },
// options: {
// encrypt: true
// }
// };
// For user-assigned managed identity.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId
// }
// };
this.poolconnection = await sql.connect(config);
如需更多資訊,請參閱 Microsoft SQL Server 用戶端程式設計的首頁。
如需更多程式代碼範例,請參閱透過服務連接器建立資料庫服務的無密碼連線。
您的程式碼中與適用於 MySQL 的 Azure 資料庫的連線,會針對所有語言堆疊遵循 DefaultAzureCredential 模式。
DefaultAzureCredential 有足夠的彈性,可適應開發環境和 Azure 環境。 在本機執行時,它可以從您選擇的環境 (Visual Studio、Visual Studio Code、Azure CLI 或 Azure PowerShell) 擷取登入的 Azure 使用者。 在 Azure 中執行時,它會擷取受控識別。 因此,在開發階段和生產環境中,都能夠連線到資料庫。 模式如下所示︰
- 從 Azure 身分識別用戶端程式庫具現化
DefaultAzureCredential。 如果您使用的是使用者指派身分識別,請指定身分識別的用戶端識別碼。
- 取得適用於 MySQL 的 Azure 資料庫的存取權杖:
https://ossrdbms-aad.database.windows.net/.default。
- 將權杖新增至連接字串。
- 開啟連線。
針對 .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");
// });
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
在您的 pom.xml 中新增下列相依性:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
從環境變數取得連接字串,並新增外掛程式名稱以連線到資料庫:
String url = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.mysql.AzureMysqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&defaultAuthenticationPlugin=" +
pluginName + "&authenticationPlugins=" + pluginName);
如需更多資訊,請參閱搭配使用 Java 和 JDBC 與適用於 MySQL 的 Azure 資料庫 (彈性伺服器)。
安裝相依性。
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
使用 azure-identity 程式庫的存取權杖進行驗證。 從服務連接器新增的環境變數取得連線資訊。 使用下列程式代碼時,請確保您取消註解您想要使用的對應至驗證類型代碼段部分。
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import mysql.connector
import os
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity.
# cred = ManagedIdentityCredential()
# For user-assigned managed identity.
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# open connect to Azure MySQL with the access token.
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token
cnx = mysql.connector.connect(user=user,
password=password,
host=host,
database=database)
cnx.close()
安裝相依性。
npm install --save @azure/identity
npm install --save mysql2
從 Service Connector 新增的環境變數中,使用 @azure/identity 和 Azure MySQL 資料庫資訊取得存取權杖。 使用下列程式代碼時,請確保您取消註解您想要使用的對應至驗證類型代碼段部分。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines according to the authentication type.
// for system-assigned managed identity
// const credential = new DefaultAzureCredential();
// for user-assigned managed identity
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: accessToken.token,
database: process.env.AZURE_MYSQL_DATABASE,
port: process.env.AZURE_MYSQL_PORT,
ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database');
});
如需更多程式代碼範例,請參閱透過服務連接器建立資料庫服務的無密碼連線。
您的程式碼中與適用於 PostgreSQL 的 Azure 資料庫的連線,會針對所有語言堆疊遵循 DefaultAzureCredential 模式。
DefaultAzureCredential 有足夠的彈性,可適應開發環境和 Azure 環境。 在本機執行時,它可以從您選擇的環境 (Visual Studio、Visual Studio Code、Azure CLI 或 Azure PowerShell) 擷取登入的 Azure 使用者。 在 Azure 中執行時,它會擷取受控識別。 因此,在開發階段和生產環境中,都能夠連線到資料庫。 模式如下所示︰
- 從 Azure 身分識別用戶端程式庫具現化
DefaultAzureCredential。 如果您使用的是使用者指派身分識別,請指定身分識別的用戶端識別碼。
- 取得適用於 PostgreSQL 的 Azure 資料庫的存取權杖:
https://ossrdbms-aad.database.windows.net/.default。
- 將權杖新增至連接字串。
- 開啟連線。
針對 .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");
// }
// );
// 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
使用來自 azure-identity 連結庫的存取權杖進行驗證,並使用權杖作為密碼。 從服務連接器新增的環境變數取得連線資訊。 使用下列程式代碼時,請確保您取消註解您想要使用的對應至驗證類型代碼段部分。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# 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)
# 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)
如需詳細資訊,請參閱以下資源:
安裝相依性。
npm install --save @azure/identity
npm install --save pg
在程式碼中,從 Service Connector 服務新增的環境變數中,透過 @azure/identity 和 PostgreSQL 連線資訊取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請確保您取消註解您想要使用的對應至驗證類型代碼段部分。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines according to the authentication type.
// 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
// });
// 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();
})();
如需更多程式代碼範例,請參閱透過服務連接器建立資料庫服務的無密碼連線。
4.設定開發環境
此範例程式代碼會使用 DefaultAzureCredential 從 Microsoft Entra ID 取得 Azure 資料庫的可用令牌,然後將它新增至資料庫連線。 雖然您可以自訂 DefaultAzureCredential,但其已預設為通用。 這會根據您的執行位置為本機開發環境或 App Service,以從登入的 Microsoft Entra 使用者或受控識別取得權杖。
程式碼不需任何進一步的變更,即已準備就緒可在 Azure 中執行。 不過,若要在本機對程式碼進行偵錯,開發環境需要使用登入的 Microsoft Entra 使用者。 在此步驟中,您會以 Microsoft Entra 使用者身分登入,來設定所選環境。
Visual Studio for Windows 會與 Microsoft Entra 驗證整合。 若要啟用 Visual Studio 中的開發和偵錯功能,請從功能表中選取 [檔案]>[帳戶設定],然後選取 [登入] 或 [新增],以在 Visual Studio 中新增您的 Microsoft Entra 使用者。
若要設定 Azure 服務驗證的 Microsoft Entra 使用者,請從功能表中選取 [工具]>[選項],然後選取 [Azure 服務驗證]>[帳戶選取]。 選取您新增的 Microsoft Entra 使用者,然後選取 [確定]。
Visual Studio for Mac 不會與 Microsoft Entra 驗證整合。 不過,Azure 身分識別用戶端程式庫 (您稍後會使用) 也可以從 Azure CLI 擷取權杖。 若要啟用 Visual Studio 中的開發和偵錯功能,請在本機電腦上安裝 Azure CLI。
使用 Microsoft Entra 使用者以下列命令登入 Azure CLI:
az login --allow-no-subscriptions
Visual Studio Code 會透過 Azure 延伸模組整合 Microsoft Entra 驗證。 在 Visual Studio Code 中,安裝 Azure Tools 延伸模組。
在 Visual Studio Code 的活動列上,選取 Azure 標誌。
在 [App Service] 總管中,選取 [登入 Azure...],然後遵循指示進行。
Azure 身分識別用戶端程式庫 (您稍後會用到),也可以使用來自 Azure CLI 的權杖。 若要啟用以命令列為基礎的開發,請在本機電腦上安裝 Azure CLI。
使用 Microsoft Entra 使用者以下列命令登入 Azure:
az login --allow-no-subscriptions
Azure 身分識別用戶端程式庫 (您稍後會用到),也可以使用來自 Azure PowerShell 的權杖。 若要啟用以命令列為基礎的開發,請在本機電腦上安裝 Azure PowerShell。
使用 Microsoft Entra 使用者以下列 Cmdlet 登入 Azure CLI:
Connect-AzAccount
如需如何設定 Microsoft Entra 驗證開發環境的詳細資訊,請參閱適用於 .NET 的 Azure 身分識別用戶端程式庫。
現在您已可開始將 SQL Database 作為後端,使用 Microsoft Entra 驗證開發和偵錯您的應用程式。
5.儲存並發佈
在開發環境中執行您的程式碼。 程式碼會在環境中使用登入的 Microsoft Entra 使用者,連線到後端資料庫。 由於該使用者已設定為資料庫的 Microsoft Entra 系統管理員,因此可以存取資料庫。
使用慣用的發佈方法將您的程式碼發佈至 Azure。 在 App Service 中,程式碼會使用應用程式的受控識別來連線到後端資料庫。
常見問題集
受控識別是否支援 SQL Server?
是。 如需詳細資訊,請參閱
我收到下列錯誤 Login failed for user '<token-identified principal>'.
您嘗試要求權杖的受控識別未獲授權存取 Azure 資料庫。
我已變更 App Service 驗證或相關聯的應用程式註冊。 為什麼仍會取得舊的權杖?
受控識別的後端服務也會維護權杖快取;只有當權杖過期時,才會為目標資源更新其權杖。 如果您在嘗試透過應用程式取得權杖「之後」修改設定,實際上要等到快取的權杖過期,您才會取得具有更新權限的新權杖。 若要解決此問題,最佳方式是使用新的 InPrivate (Edge)/private (Safari)/Incognito (Chrome) 視窗來測試變更。 這樣就一定會從全新的已驗證工作階段開始。
如何將受控識別新增至 Microsoft Entra 群組?
如有需要,您可以將身分識別新增至 Microsoft Entra 群組,然後將存取權授與 Microsoft Entra 群組,而不是身分識別。 例如,下列命令會將上一個步驟中的受控識別新增至名為 myAzureSQLDBAccessGroup 的新群組:
groupid=$(az ad group create --display-name myAzureSQLDBAccessGroup --mail-nickname myAzureSQLDBAccessGroup --query objectId --output tsv)
msiobjectid=$(az webapp identity show --resource-group <group-name> --name <app-name> --query principalId --output tsv)
az ad group member add --group $groupid --member-id $msiobjectid
az ad group member list -g $groupid
若要授與 Microsoft Entra 群組的資料庫權限,請參閱個別資料庫類型的文件。
我收到下列錯誤 SSL connection is required. Please specify SSL options and retry。
連線到 Azure 資料庫需要額外的設定,而這些資訊不在本教學課程的涵蓋範圍內。 如需詳細資訊,請參閱下列其中一個連結:
在適用於 PostgreSQL 的 Azure 資料庫 - 單一伺服器中設定 TLS 連線能力在您的應用程式中設定 SSL 連線能力,以安全地連線至適用於 MySQL 的 Azure 資料庫
Service Connector 需要資料庫的網路存取權,才能授與應用程式身分識別的存取權。 當您使用 Web 應用程式 + 資料庫範本在 Azure 入口網站中建立安全的應用程式和資料庫架構時,架構會鎖定資料庫的網路存取權,並且只允許虛擬網路內的連線。 Azure Cloud Shell 也是如此。 不過,您可以在虛擬網路中部署 Cloud Shell,然後在該 Cloud Shell 中執行 Service Connector 命令。
下一步
您已了解如何︰
- 將 Microsoft Entra 使用者設定為 Azure 資料庫的系統管理員。
- 以 Microsoft Entra 使用者身分連線到您的資料庫。
- 為 App Service 應用程式設定系統指派或使用者指派的受控識別。
- 將資料庫存取權授與受控識別。
- 使用受控識別,透過程式碼 (.NET Framework 4.8、.NET 6、Node.js、Python、Java) 連線到 Azure 資料庫。
- 使用 Microsoft Entra 使用者,透過開發環境連線到 Azure 資料庫。