無密碼連線會使用受控識別來存取 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 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
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type $CLIENT_TYPE
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=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
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--system-identity mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=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
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type dotnet
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX \
--client-type dotnet
使用 --client-type 參數執行下列 Azure CLI 命令。 執行 az webapp connection create fabricsql -h 以取得支援的用戶端類型,然後選擇符合應用程式的用戶端類型。
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
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 \
--system-identity \
--client-type dotnet
附註
以 Microsoft Fabric 中的 SQL 資料庫為目標時,不支援使用服務主體的服務連線。
此服務連接器命令會在背景中完成下列工作:
- 啟用系統指派的受控識別,或為 Azure App Service/Azure Spring 應用程式/Azure 容器應用程式所裝載的應用程式
$APPSERVICE_NAME 指派使用者身分識別。
- 為資料庫伺服器啟用 Microsoft Entra 驗證 (如果尚未啟用)。
- 將 Microsoft Entra 系統管理員設定為目前的登入使用者。
- 為系統指派的受控識別、使用者指派的受控識別或服務主體新增資料庫使用者。 將資料庫的所有權限
$DATABASE_NAME 授與此使用者。 您可以在上述指令輸出中的連接字串中找到使用者名稱。
- 根據資料庫類型,將名為
AZURE_MYSQL_CONNECTIONSTRING、 AZURE_POSTGRESQL_CONNECTIONSTRING、 AZURE_SQL_CONNECTIONSTRING或 FABRIC_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();
}
在 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 搭配您慣用的程式庫來取得存取權杖。
對於使用者指派身份與系統指派身份,Azure App Service 與 Azure Container Apps 提供內部可存取的 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 連線資訊來取得存取權杖。 結合它們以建立連線。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
Azure App Service 與 Azure Container Apps 提供內部可存取的 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
在 .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
在 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";
Properties properties = new Properties();
properties.put("defaultAuthenticationPlugin", pluginName);
properties.put("authenticationPlugins", pluginName);
// Uncomment the following lines corresponding to the authentication type you want to use.
// for user-assigned managed identity
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// properties.put("azure.clientId", clientId);
// For service principal
// String tenantId = System.getenv('AZURE_MYSQL_TENANTID')
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// String clientSecret = System.getenv('AZURE_MYSQL_CLIENTSECRET')
// properties.put("azure.clientId", clientId);
// properties.put("azure.clientSecret", clientSecret);
// properties.put("azure.tenantId", tenantId);
Connection connection = DriverManager.getConnection(url, properties);
如需詳細資訊,請參閱 搭配適用於 MySQL 的 Azure 資料庫使用 Java 和 JDBC - 彈性伺服器。
安裝相依性
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 corresponding to the authentication type you want to use.
# 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)
# For service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# 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()
安裝相依性。
pip install azure-identity
使用服務連接器新增的環境變數,透過 azure-identity 程式庫取得存取權杖。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# system-assigned managed identity
# cred = ManagedIdentityCredential()
# user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
在設定檔案中,從服務連接器服務新增的環境變數取得 Azure MySQL 資料庫資訊。 使用在前一步驟中取得的 accessToken 來存取資料庫。
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
安裝相依性。
go get "github.com/go-sql-driver/mysql"
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在程式碼中,透過 azidentity 取得存取權杖,然後使用該權杖連線到 Azure MySQL。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/go-sql-driver/mysql"
)
func main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// for user-assigned managed identity
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// for service principal
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// tenantid := os.Getenv("AZURE_MYSQL_TENANTID")
// clientsecret := os.Getenv("AZURE_MYSQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
}
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"),
})
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING") + ";Password=" + token.Token
db, err := sql.Open("mysql", connectionString)
}
安裝相依性
npm install --save @azure/identity
npm install --save mysql2
使用 @azure/identity 以及從服務連接器服務新增的環境變數取得的 Azure MySQL 資料庫資訊,取得存取權杖。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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
// });
// for service principal
// const tenantId = process.env.AZURE_MYSQL_TENANTID;
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const clientSecret = process.env.AZURE_MYSQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// 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');
});
如需更多程式代碼範例,請參閱 使用受控識別從 App Service 連線到 Azure 資料庫,而不使用秘密。
安裝相依性。
dotnet add package Microsoft.Data.SqlClient
從服務連接器新增的環境變數取得 Azure SQL Database 連結字串。
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
如需詳細資訊,請參閱 使用 Active Directory 受控識別驗證。
在 pom.xml 檔案中新增下列相依性:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</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;"
// For service principal: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};user={ServicePrincipalClientId};password={spSecret};authentication=ActiveDirectoryServicePrincipal;"
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();
}
}
}
如需詳細資訊,請參閱 使用託管身份而不使用機密從 App Service 連線到 Azure 資料庫。
在 Spring 應用程式中,如果您使用選項 --client-type springboot 建立連線,服務連接器會將具有值格式 spring.datasource.url 的屬性 jdbc:sqlserver://<sql-server>.database.windows.net:1433;databaseName=<sql-db>;authentication=ActiveDirectoryMSI; 設定為 Azure Spring 應用程式。
依照教學課程移轉 JAVA 應用程式以使用無密碼連線和 Azure SQL Database 來更新應用程式。 如果之前已設定 spring.datasource.password 設定屬性,請記得要移除它,然後新增正確的相依性。
安裝相依性。
python -m pip install pyodbc
從服務連接器新增的環境變數取得 Azure SQL Database 連結組態。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。 如果您使用 Azure Container Apps 作為計算服務,或代碼段中的連接字串無法運作,請參閱 移轉 Python 應用程式以使用 Azure SQL Database 的無密碼連線 ,以使用存取令牌連線到 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')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For user-assigned managed identity.
# clientID = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={clientID};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For service principal.
# user = os.getenv('AZURE_SQL_USER')
# password = os.getenv('AZURE_SQL_PASSWORD')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={user};PWD={password};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
conn = pyodbc.connect(connString)
- 安裝相依性。
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 corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// const config = {
// server,
// port,
// database,
// authentication: {
// type: 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
// }
// };
// For service principal.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const clientSecret = process.env.AZURE_SQL_CLIENTSECRET;
// const tenantId = process.env.AZURE_SQL_TENANTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId,
// clientSecret: clientSecret,
// tenantId: tenantId
// }
// };
this.poolconnection = await sql.connect(config);
如需更多資訊,請參閱 Microsoft SQL Server 用戶端程式開發資源頁面。
安裝相依性。
dotnet add package Microsoft.Data.SqlClient
從 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 受控識別驗證。
在 pom.xml 檔案中新增下列相依性:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</version>
</dependency>
從 Service Connector 新增的環境變數擷取 Microsoft Fabric 連接字串中的 SQL 資料庫。
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) {
// FABRIC_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;msiClientId=<msiClientId>;authentication=ActiveDirectoryMSI;"
String connectionString = System.getenv("FABRIC_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
如需詳細資訊,請參閱 使用託管身份而不使用機密從 App Service 連線到 Azure 資料庫。
如果是 Spring 應用程式,如果您建立具有 選項--client-type springboot的連線,Service Connector 會將具有值格式FABRIC_SQL_CONNECTIONSTRING的環境變數jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;設定為 Azure Spring Apps。
針對使用者指派的受控識別,會新增 msiClientId=<msiClientId>;。
依照教學課程移轉 JAVA 應用程式以使用無密碼連線和 Azure SQL Database 來更新應用程式。 如果先前已設定 spring.datasource.password 組態屬性,請記得移除它並新增正確的相依性。
spring:
datasource:
url: ${FABRIC_SQL_CONNECTIONSTRING}
安裝相依性。
python -m pip install pyodbc
從 Service Connector 新增的環境變數擷取 Microsoft Fabric 連接字串中的 SQL 資料庫。 如果您使用 Azure Container Apps 作為計算服務,或代碼段中的連接字串無法運作,請參閱 移轉 Python 應用程式以使用 Azure SQL Database 的無密碼連線 ,以使用無密碼認證連線到 Microsoft Fabric 中的 SQL 資料庫。
Authentication=ActiveDirectoryMSI; 在使用受控身份進行連線時,必須在連接字串中包含。
使用使用者指派的受控識別進行連線時,連接字串中也需要 UID=<msiClientId>。
import os
import pyodbc, struct
from azure.identity import DefaultAzureCredential
connStr = os.getenv('FABRIC_SQL_CONNECTIONSTRING')
# System-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;Authentication=ActiveDirectoryMSI;`
# User-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;UID=<msiClientId>;Authentication=ActiveDirectoryMSI;`
conn = pyodbc.connect(connString)
- 安裝相依性。
go mod init <YourProjectName>
go mod tidy
- 從 Service Connector 新增的環境變數擷取 Microsoft Fabric 連接字串中的 SQL 資料庫。
package main
import (
"github.com/microsoft/go-mssqldb/azuread"
"database/sql"
"context"
"log"
"fmt"
"os"
)
var db *sql.DB
var connectionString = os.Getenv("FABRIC_SQL_CONNECTIONSTRING")
func main() {
var err error
// Create connection pool
db, err = sql.Open(azuread.DriverName, connectionString)
if err != nil {
log.Fatal("Error creating connection pool: ", err.Error())
}
ctx := context.Background()
err = db.PingContext(ctx)
if err != nil {
log.Fatal(err.Error())
}
fmt.Printf("Connected!\n")
}
如需詳細資訊,請參閱 使用 Golang 查詢 Azure SQL Database 中的資料庫。
如需詳細資訊,請參閱 在 Microsoft Fabric 中聯機到 SQL 資料庫。
將應用程式部署至 Azure 裝載服務
將您的應用程式部署至 Azure 主控服務。 如需部署這些資源的詳細資訊,請選擇性地參閱下列指南。
檢查記錄檔或呼叫應用程式,以查看是否可以成功連線到 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 和無密碼連線的詳細資訊,請參閱下列資源: