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();
}
如果是 Spring 應用程式,如果您建立具有 選項--client-type springboot的連線,則 Service 連線 or 會將屬性 spring.datasource.azure.passwordless-enabled、 spring.datasource.url和 spring.datasource.username 設定為 Azure Spring Apps。
遵循將 適用於 PostgreSQL 的 Azure 資料庫 系結至 Azure Spring Apps 中的應用程式教學課程,更新您的應用程式。 spring.datasource.password請記得在之前設定組態屬性,並將正確的相依性新增至 Spring 應用程式。
使用連結庫取得 azure-identity 存取令牌,並使用令牌作為密碼。 從 Service 連線 or 所新增的環境變數取得連線資訊。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。
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)
# 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
使用 Service 連線 or 新增的環境變數,使用azure-identity連結庫取得存取令牌。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# 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')
在配置檔中,從 Service 連線 or 服務新增的環境變數取得 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,以及 Service 連線 or 所提供的連線資訊。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。
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 according to the authentication type.
// 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()
在程式代碼中,使用 @azure/identity 和 PostgreSQL 連線資訊,從 Service 連線 or 服務新增的環境變數取得存取令牌。 將它們結合以建立連線。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。
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
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_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 搭配您慣用的連結庫來取得存取令牌。
針對使用者指派的身分識別和系統指派的身分識別,App Service 和 Container Apps 提供內部可存取的 REST 端點,藉由定義兩個環境變數來擷取受控識別的令牌: IDENTITY_ENDPOINT 和 IDENTITY_HEADER。 如需詳細資訊,請參閱 REST 端點參考。
對身分識別端點提出 HTTP GET 要求,並在 https://ossrdbms-aad.database.windows.net 查詢中使用, resource 以取得存取令牌。 針對使用者指派的身分識別,請同時在查詢中包含 Service 連線 or 所新增環境變數的用戶端識別符。
如需服務主體,請參閱 Azure AD 服務對服務存取令牌要求 ,以查看如何取得存取令牌的詳細數據。 從 Service 連線 or 所新增的環境變數,將 POST 要求設為 和 的範圍https://ossrdbms-aad.database.windows.net/.default,以及服務主體的租使用者標識碼、用戶端標識碼和客戶端密碼。
結合 Service 連線 or 服務所新增環境變數的存取令牌和 PostgreSQL 連線 sting,以建立連線。
接下來,如果您已在 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
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
如果是 Spring 應用程式,如果您建立具有 選項--client-type springboot的連線,則服務 連線 or 會將屬性 spring.datasource.azure.passwordless-enabled、 spring.datasource.url和 spring.datasource.username 設定為 Azure Spring Apps。
透過連結azure-identity庫取得存取令牌進行驗證,並從 Service 連線 or 所新增的環境變數取得連線資訊。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。
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)
# 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連結庫取得存取令牌,其中包含 Service 連線 or 所新增的環境變數。 使用下列程式代碼時,請取消批註您想要使用的驗證類型代碼段部分。
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import os
# Uncomment the following lines according to the authentication type.
# 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')
在配置檔中,從 Service 連線 or 服務新增的環境變數取得 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"
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
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的連線,則 Service 連線 or 會將具有值格式jdbc:sqlserver://<sql-server>.database.windows.net:1433;databaseName=<sql-db>;authentication=ActiveDirectoryMSI;的屬性spring.datasource.url設定為 Azure Spring Apps。
將 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 命令登入。