Esercitazione: Creare una connessione senza password a un servizio di database tramite Service Connessione or
Articolo
Le connessioni senza password usano identità gestite per accedere ai servizi di Azure. Con questo approccio non è necessario tenere traccia e gestire manualmente i segreti per le identità gestite. Queste attività vengono gestite internamente da Azure.
Service Connessione or abilita le identità gestite nei servizi di hosting di app come Azure Spring Apps, app Azure Service e App Azure Container. Service Connessione or configura anche i servizi di database, ad esempio Database di Azure per PostgreSQL, Database di Azure per MySQL e database SQL di Azure, per accettare le identità gestite.
In questa esercitazione verrà usata l'interfaccia della riga di comando di Azure per completare le attività seguenti:
Controllare l'ambiente iniziale con l'interfaccia della riga di comando di Azure.
Creare una connessione senza password con Service Connessione or.
Usare le variabili di ambiente o le configurazioni generate da Service Connessione or per accedere a un servizio di database.
Accedere con l'interfaccia della riga di comando di Azure tramite az login. Se si usa Azure Cloud Shell o si è già connessi, confermare l'account autenticato con az account show.
Installare l'estensione senza password del servizio Connessione or
Installare l'estensione senza password del servizio Connessione or per l'interfaccia della riga di comando di Azure:
az extension add --name serviceconnector-passwordless --upgrade
Creare una connessione senza password
Si userà quindi app Azure Servizio come esempio per creare una connessione usando l'identità gestita.
Se si usa la portale di Azure, passare al pannello Service Connessione or (Service Connessione or) di app Azure Service (Servizio), Azure Spring Apps (App Azure Spring) o Azure Container Apps (App Azure Container) e selezionare Crea per creare una connessione. Il portale di Azure comporrà automaticamente il comando e attiverà l'esecuzione del comando in Cloud Shell.
Il comando seguente dell'interfaccia della riga di comando di Azure usa un --client-type parametro . az webapp connection create postgres-flexible -h Eseguire per ottenere i tipi di client supportati e scegliere quello che corrisponde all'applicazione.
Database di Azure per MySQL : il server flessibile richiede un'identità gestita assegnata dall'utente per abilitare l'autenticazione di Microsoft Entra. Per altre informazioni, vedere Configurare l'autenticazione di Microsoft Entra per Database di Azure per MySQL - Server flessibile. È possibile usare il comando seguente per creare un'identità gestita assegnata dall'utente:
Dopo aver creato l'identità gestita assegnata dall'utente, chiedere all'Amministrazione istrator globale o al ruolo con privilegi Amministrazione istrator di concedere le autorizzazioni seguenti per questa identità:
Connettere quindi l'app a un database MySQL con un'identità gestita assegnata dal sistema usando Service Connessione or.
Il comando seguente dell'interfaccia della riga di comando di Azure usa un --client-type parametro . az webapp connection create mysql-flexible -h Eseguire per ottenere i tipi di client supportati e scegliere quello che corrisponde all'applicazione.
Il comando seguente dell'interfaccia della riga di comando di Azure usa un --client-type parametro . az webapp connection create sql -h Eseguire per ottenere i tipi di client supportati e scegliere quello che corrisponde all'applicazione.
Questo comando service Connessione or completa le attività seguenti in background:
Abilitare l'identità gestita assegnata dal sistema o assegnare un'identità utente per l'app $APPSERVICE_NAME ospitata da app Azure Servizio/App Spring di Azure/App Azure Container.
Impostare l'amministratore di Microsoft Entra sull'utente connesso corrente.
Aggiungere un utente del database per l'identità gestita assegnata dal sistema, l'identità gestita assegnata dall'utente o l'entità servizio. Concedere a questo utente tutti i privilegi del database $DATABASE_NAME . Il nome utente è disponibile nella stringa di connessione nell'output del comando precedente.
Impostare le configurazioni denominate AZURE_MYSQL_CONNECTIONSTRING, AZURE_POSTGRESQL_CONNECTIONSTRINGo AZURE_SQL_CONNECTIONSTRING sulla risorsa di Azure in base al tipo di database.
Per servizio app, le configurazioni vengono impostate nel pannello App Impostazioni.
Per Spring Apps, le configurazioni vengono impostate all'avvio dell'applicazione.
Per App contenitore, le configurazioni vengono impostate sulle variabili di ambiente. È possibile ottenere tutte le configurazioni e i relativi valori nel pannello Service Connessione or nel portale di Azure.
Connessione a un database con l'autenticazione di Microsoft Entra
Dopo aver creato la connessione, è possibile usare il stringa di connessione nell'applicazione per connettersi al database con l'autenticazione Microsoft Entra. Ad esempio, è possibile usare le soluzioni seguenti per connettersi al database con l'autenticazione di Microsoft Entra.
Per .NET non è disponibile un plug-in o una libreria per supportare connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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();
}
Aggiungere le dipendenze seguenti nel file pom.xml :
Per un'applicazione Spring, se si crea una connessione con l'opzione --client-type springboot, Service Connessione or imposta le proprietà spring.datasource.azure.passwordless-enabled, spring.datasource.urle spring.datasource.username su Azure Spring Apps.
Ottenere il token di accesso usando azure-identity la libreria e usare il token come password. Ottenere informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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)
Installare le dipendenze.
pip install azure-identity
Ottenere il token di accesso usando la azure-identity libreria usando le variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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')
Nel file di impostazione ottenere informazioni sul database PostgreSQL di Azure dalle variabili di ambiente aggiunte dal servizio Connessione or. Usare accessToken acquisito nel passaggio precedente per accedere al database.
# 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'},
}
}
Installare le dipendenze.
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"
Nel codice ottenere il token di accesso usando azidentity, quindi usarlo come password per connettersi ad Azure PostgreSQL insieme alle informazioni di connessione fornite da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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()
Nel codice ottenere il token di accesso usando @azure/identity e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio service Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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();
})();
Per PHP, non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Nel codice ottenere il token di accesso usando l'API REST con la libreria preferita.
Per l'identità assegnata dall'utente e l'identità assegnata dal sistema, servizio app e App contenitore fornisce un endpoint REST accessibile internamente per recuperare i token per le identità gestite definendo due variabili di ambiente: IDENTITY_ENDPOINT e IDENTITY_HEADER. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
Ottenere il token di accesso effettuando una richiesta HTTP GET all'endpoint di identità e usarlo https://ossrdbms-aad.database.windows.net come resource nella query. Per l'identità assegnata dall'utente, includere anche l'ID client dalle variabili di ambiente aggiunte da Service Connessione or nella query.
Per l'entità servizio, vedere la richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare i dettagli su come acquisire il token di accesso. Effettuare la richiesta POST per l'ambito di https://ossrdbms-aad.database.windows.net/.default e con l'ID tenant, l'ID client e il segreto client dell'entità servizio dalle variabili di ambiente aggiunte da Service Connessione or.
Combinare il token di accesso e l'sting della connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or per stabilire la connessione.
Per Ruby non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Installare le dipendenze.
gem install pg
Nel codice ottenere il token di accesso usando l'API REST e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Il servizio app e le app del contenitore forniscono un endpoint REST accessibile internamente per recuperare i token per le identità gestite. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines according to the authentication type.
# 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,
)
Fare riferimento alla richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare altri dettagli su come acquisire il token di accesso per l'entità servizio.
Per altre lingue, usare le proprietà di connessione impostate da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per PostgreSQL con Service Connessione or.
Successivamente, se sono state create tabelle e sequenze nel server flessibile PostgreSQL prima di usare Service Connessione or, è necessario connettersi come proprietario e concedere l'autorizzazione a <aad-username> creata da Service Connessione or. Il nome utente del stringa di connessione o della configurazione impostato da Service Connessione or dovrebbe essere simile aad_<connection name>a . Se si usa il portale di Azure, selezionare il pulsante di espansione accanto alla Service Type colonna e ottenere il valore. Se si usa l'interfaccia della riga di comando di Azure, archiviare configurations l'output del comando dell'interfaccia della riga di comando.
Eseguire quindi la query per concedere l'autorizzazione
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> e <owner-password> è il proprietario della tabella esistente che può concedere autorizzazioni ad altri utenti. <aad-username>è l'utente creato da Service Connessione or. Sostituirli con il valore effettivo.
Convalidare il risultato con il comando :
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
Per .NET non è disponibile un plug-in o una libreria per supportare connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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
Aggiungere le dipendenze seguenti nel file pom.xml :
Per un'applicazione Spring, se si crea una connessione con l'opzione --client-type springboot, Service Connessione or imposta le proprietà spring.datasource.azure.passwordless-enabled, spring.datasource.urle spring.datasource.username su Azure Spring Apps.
Eseguire l'autenticazione con il token di accesso tramite azure-identity libreria e ottenere informazioni di connessione dalla variabile di ambiente aggiunta da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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()
Installare le dipendenze.
pip install azure-identity
Ottenere il token di accesso tramite azure-identity libreria con le variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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')
Nel file di impostazione ottenere informazioni sul database MySQL di Azure dalle variabili di ambiente aggiunte dal servizio Connessione or. Usare accessToken acquisito nel passaggio precedente per accedere al database.
# 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
}
}
Installare le dipendenze.
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"
Nel codice ottenere il token di accesso tramite azidentity, quindi connettersi ad Azure MySQL con il token. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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 according to the authentication type.
// 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)
}
Ottenere il token di accesso usando @azure/identity e le informazioni sul database MySQL di Azure dalle variabili di ambiente aggiunte dal servizio Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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
// });
// 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');
});
Per altre lingue, usare il stringa di connessione e il nome utente impostati da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per MySQL con Service Connessione or.
Per altre lingue, usare il stringa di connessione e il nome utente impostati da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per MySQL con Service Connessione or.
Per altre lingue, usare le proprietà di connessione impostate da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per MySQL con Service Connessione or.
Ottenere il database SQL di Azure stringa di connessione dalla variabile di ambiente aggiunta da Service Connessione or.
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
Ottenere il database SQL di Azure stringa di connessione dalla variabile di ambiente aggiunta da Service Connessione or.
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();
}
}
}
Per un'applicazione Spring, se si crea una connessione con l'opzione --client-type springboot, Service Connessione or imposta le proprietà spring.datasource.url con formato jdbc:sqlserver://<sql-server>.database.windows.net:1433;databaseName=<sql-db>;authentication=ActiveDirectoryMSI; valore su Azure Spring Apps.
Ottenere le configurazioni di connessione database SQL di Azure dalla variabile di ambiente aggiunta da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
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 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.
# user = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server={server},{port};Database={database};UID={user};Authentication={authentication};Encrypt=yes;'
# 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={server},{port};Database={database};UID={user};PWD={password};Authentication={authentication};Encrypt=yes;'
conn = pyodbc.connect(connString)
Installare le dipendenze.
npm install mssql
Ottenere le configurazioni di connessione database SQL di Azure dalle variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Per altre lingue, usare le proprietà di connessione impostate da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare database SQL di Azure con Service Connessione or.
Distribuire l'applicazione in un servizio di hosting di Azure
Distribuire infine l'applicazione in un servizio di hosting di Azure. Il servizio di origine può usare un'identità gestita per connettersi al database di destinazione in Azure.
Per app Azure Servizio, è possibile distribuire il codice dell'applicazione tramite il az webapp deploy comando . Per altre informazioni, vedere Guida introduttiva: Distribuire un'app Web ASP.NET.
Per le app contenitore di Azure, è possibile distribuire il codice dell'applicazione tramite il az containerapp create comando . Per altre informazioni, vedere Avvio rapido: Distribuire la prima app contenitore.
È quindi possibile controllare il log o chiamare l'applicazione per verificare se è in grado di connettersi correttamente al database di Azure.
Risoluzione dei problemi
Autorizzazione
Se si verificano errori correlati alle autorizzazioni, verificare che l'utente connesso all'interfaccia della riga di comando di Azure con il comando az account show. Assicurarsi di accedere con l'account corretto. Verificare quindi di avere le autorizzazioni seguenti che potrebbero essere necessarie per creare una connessione senza password con Service Connessione or.
Autorizzazione
Operazione
Microsoft.DBforPostgreSQL/flexibleServers/read
Obbligatorio per ottenere informazioni sul server di database
Microsoft.DBforPostgreSQL/flexibleServers/write
Obbligatorio per abilitare l'autenticazione di Microsoft Entra per il server di database
Obbligatorio per aggiungere l'utente di accesso dell'interfaccia della riga di comando di Azure come amministratore di Microsoft Entra del server di database
Autorizzazione
Operazione
Microsoft.DBforMySQL/flexibleServers/read
Obbligatorio per ottenere informazioni sul server di database
Microsoft.DBforMySQL/flexibleServers/write
Obbligatorio per aggiungere l'identità gestita assegnata dall'utente al server di database
Obbligatorio per aggiungere l'utente di accesso dell'interfaccia della riga di comando di Azure come amministratore di Microsoft Entra del server di database
Autorizzazione
Operazione
Microsoft.Sql/servers/read
Obbligatorio per ottenere informazioni sul server di database
Microsoft.Sql/servers/firewallRules/write
Obbligatorio per creare una regola del firewall nel caso in cui l'indirizzo IP locale sia bloccato
Microsoft.Sql/servers/firewallRules/delete
Necessario per ripristinare la regola del firewall creata dal Connessione or del servizio per evitare problemi di sicurezza
Microsoft.Sql/servers/administrators/read
Obbligatorio per verificare se l'utente di accesso dell'interfaccia della riga di comando di Azure è un amministratore di Microsoft Entra
Microsoft.Sql/servers/administrators/write
Obbligatorio per aggiungere l'utente di accesso dell'interfaccia della riga di comando di Azure come amministratore di Microsoft Entra del server di database
In alcuni casi, le autorizzazioni non sono necessarie. Ad esempio, se l'utente autenticato dall'interfaccia della riga di comando di Azure è già un'istanza di Active Directory Amministrazione istrator in SQL Server, non è necessario disporre dell'autorizzazioneMicrosoft.Sql/servers/administrators/write.
Microsoft Entra ID
Se viene visualizzato un errore ERROR: AADSTS530003: Your device is required to be managed to access this resource., chiedere al reparto IT di assistenza per l'aggiunta di questo dispositivo all'ID Microsoft Entra. Per altre informazioni, vedere Dispositivi aggiunti a Microsoft Entra.
Service Connessione or deve accedere all'ID Microsoft Entra per ottenere informazioni sull'account e sull'identità gestita del servizio di hosting. È possibile usare il comando seguente per verificare se il dispositivo può accedere all'ID Microsoft Entra:
az ad signed-in-user show
Se non si esegue l'accesso in modo interattivo, è anche possibile che venga visualizzato l'errore e Interactive authentication is needed. Per risolvere l'errore, accedere con il az login comando .
Connettività di rete
Se il server di database si trova in Rete virtuale, assicurarsi che l'ambiente che esegue il comando dell'interfaccia della riga di comando di Azure possa accedere al server nel Rete virtuale.
Se il server di database si trova in Rete virtuale, assicurarsi che l'ambiente che esegue il comando dell'interfaccia della riga di comando di Azure possa accedere al server nel Rete virtuale.
Se il server di database non consente l'accesso pubblico, assicurarsi che l'ambiente che esegue il comando dell'interfaccia della riga di comando di Azure possa accedere al server tramite l'endpoint privato.
Passaggi successivi
Per altre informazioni su Service Connessione or e connessioni senza password, vedere le risorse seguenti: