Integrare Database di Azure per MySQL con Service Connector

Questo articolo illustra i metodi di autenticazione supportati, i client e il codice di esempio che è possibile usare per connettere le app a Database di Azure per MySQL - Server flessibile tramite Service Connector. In questo articolo sono disponibili anche nomi, valori e configurazione predefiniti delle variabili di ambiente ottenuti durante la creazione di connessioni al servizio.

Importante

Il server singolo del Database di Azure per MySQL è in fase di ritiro. È consigliabile eseguire l'aggiornamento al server flessibile del Database di Azure per MySQL. Per altre informazioni sulla migrazione a Database di Azure per MySQL - Server flessibile, vedere Cosa succede a Database di Azure per MySQL - Server singolo?

Servizi di calcolo supportati

Service Connector può essere usato per connettere i servizi di calcolo seguenti a Database di Azure per MySQL:

  • Servizio app di Azure
  • Funzioni di Azure
  • Servizio Azure Kubernetes (AKS)
  • Azure Spring Apps

Tipi di autenticazione e tipi di client supportati

La tabella seguente illustra le combinazioni di metodi di autenticazione e client supportati per la connessione dei servizi di calcolo a Database di Azure per MySQL tramite Service Connector. Un valore "Sì" indica che la combinazione è supportata, mentre "No" indica che non è supportata.

Tipo client Identità gestita assegnata dal sistema Identità gestita assegnata dall'utente Stringa segreta/di connessione Entità servizio
.NET
Go (go-sql-driver per MySQL)
Java (JDBC)
Java - Spring Boot (JDBC)
Node.js (mysql)
Python (mysql-connector-python)
Python-Django
PHP (MySQLi)
Ruby (mysql2)
Nessuno

Nota

L'identità gestita assegnata dal sistema, l'identità gestita assegnata dall'utente e l'autenticazione dell'entità servizio sono supportate solo nell'interfaccia della riga di comando di Azure.

Nomi di variabili di ambiente predefiniti o proprietà dell'applicazione e codice di esempio

Fare riferimento ai dettagli della connessione e al codice di esempio nelle tabelle seguenti, in base al tipo di autenticazione e al tipo di client della connessione, per connettere i servizi di calcolo a Database di Azure per MySQL. Per altre informazioni sulle convenzioni di denominazione, vedere Elementi interni di Service Connector.

Identità gestita assegnata dal sistema

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_MYSQL_CONNECTIONSTRING Stringa di connessione ADO.NET MySQL Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required;

Codice di esempio

Fare riferimento ai passaggi e al codice seguenti per connettersi a Database di Azure per MySQL usando un'identità gestita assegnata dal sistema.

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 tramite una libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando utilizzi il codice seguente, decommenta la parte del frammento di codice relativa al tipo di autenticazione che desideri utilizzare.

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

Per altri esempi di codice, vedere Connettersi ai database di Azure dal servizio app senza segreti usando un'identità gestita.

Identità gestita assegnata dall'utente

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_MYSQL_CLIENTID L’ID del cliente <identity-client-ID>
AZURE_MYSQL_CONNECTIONSTRING Stringa di connessione ADO.NET MySQL Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required;

Codice di esempio

Fare riferimento ai passaggi e al codice seguenti per connettersi a Database di Azure per MySQL usando un'identità gestita assegnata dall'utente.

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 tramite una libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando utilizzi il codice seguente, decommenta la parte del frammento di codice relativa al tipo di autenticazione che desideri utilizzare.

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

Per altri esempi di codice, vedere Connettersi ai database di Azure dal servizio app senza segreti usando un'identità gestita.

Stringa di connessione

Avviso

Microsoft consiglia di usare il flusso di autenticazione più sicuro disponibile. Il flusso di autenticazione descritto in questa procedura richiede un livello di attendibilità molto elevato nell'applicazione e comporta rischi che non sono presenti in altri flussi. Si consiglia di usare questo flusso solo quando altri flussi più sicuri, come le identità gestite, non sono validi.

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_MYSQL_CONNECTIONSTRING Stringa di connessione ADO.NET MySQL Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;Password=<MySQL-DB-password>;SSL Mode=Required

Codice di esempio

Per connettersi a Database di Azure per MySQL usando una stringa di connessione, vedere i passaggi e il codice seguenti.

  1. Installare le dipendenze. Seguire le indicazioni per installare il connettore/NET MySQL
  2. Nel codice ottenere la stringa di connessione MySQL dalle variabili di ambiente aggiunte dal servizio Service Connector. Per stabilire una connessione crittografata al server MySQL tramite SSL, vedere questi passaggi.
    using System;
    using System.Data;
    using MySql.Data.MySqlClient;
    
    string connectionString = Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING");
    using (MySqlConnection connection = new MySqlConnection(connectionString))
    {
        connection.Open();
    }
    

Entità servizio

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_MYSQL_CLIENTID L’ID del cliente <client-ID>
AZURE_MYSQL_CLIENTSECRET Il segreto del client <client-secret>
AZURE_MYSQL_TENANTID ID del tenant. <tenant-ID>
AZURE_MYSQL_CONNECTIONSTRING Stringa di connessione ADO.NET MySQL Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required

Codice di esempio

Per connettersi ad Database di Azure per MySQL usando un service principal, fare riferimento ai passaggi e al codice seguenti.

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 tramite una libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando utilizzi il codice seguente, decommenta la parte del frammento di codice relativa al tipo di autenticazione che desideri utilizzare.

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

Per altri esempi di codice, vedere Connettersi ai database di Azure dal servizio app senza segreti usando un'identità gestita.

Passaggi successivi

Seguire le documentazioni per altre informazioni su Service Connector.