In dit artikel worden ondersteunde verificatiemethoden, clients en voorbeeldcode beschreven die u kunt gebruiken om uw apps te verbinden met Azure Database for MySQL - Flexible Server met behulp van Service Connector. In dit artikel vindt u ook de standaardnaam, waarden en configuratie van omgevingsvariabelen die zijn verkregen bij het maken van serviceverbindingen.
Belangrijk
Azure Database for MySQL enkele server bevindt zich op het buitengebruikstellingspad. We raden u ten zeerste aan een upgrade uit te voeren naar een flexibele Azure Database for MySQL-server. Voor meer informatie over migreren naar Azure Database for MySQL Flexibele server, zie Wat gebeurt er met Azure Database for MySQL Single Server?
Ondersteunde rekenservices
Serviceconnector kan worden gebruikt om de volgende rekenservices te verbinden met Azure Database for MySQL:
- Azure App Service
- Azure Container Apps
- Azure Functions
- Azure Kubernetes Service (AKS)
- Azure Spring Apps
Ondersteunde verificatietypen en clienttypen
In de onderstaande tabel ziet u welke combinaties van verificatiemethoden en clients worden ondersteund voor het verbinden van uw rekenservices met Azure Database for MySQL met behulp van Service Connector. Een 'Ja' geeft aan dat de combinatie wordt ondersteund, terwijl een 'Nee' aangeeft dat deze niet wordt ondersteund.
| Cliënttype |
Door het systeem toegewezen beheerde identiteit |
Door de gebruiker toegewezen beheerde identiteit |
Geheim/verbindingstekenreeks |
Service-principal |
| .NET |
Ja |
Ja |
Ja |
Ja |
| Go (go-sql-driver voor MySQL) |
Ja |
Ja |
Ja |
Ja |
| Java (JDBC) |
Ja |
Ja |
Ja |
Ja |
| Java - Spring Boot (JDBC) |
Ja |
Ja |
Ja |
Ja |
| Node.js (mysql) |
Ja |
Ja |
Ja |
Ja |
| Python (mysql-connector-python) |
Ja |
Ja |
Ja |
Ja |
| Python-Django |
Ja |
Ja |
Ja |
Ja |
| PHP (MySQLi) |
Ja |
Ja |
Ja |
Ja |
| Ruby (mysql2) |
Ja |
Ja |
Ja |
Ja |
| Geen |
Ja |
Ja |
Ja |
Ja |
Notitie
Door het systeem toegewezen beheerde identiteit, door de gebruiker toegewezen beheerde identiteit en verificatie van service-principals wordt alleen ondersteund in Azure CLI.
Namen van standaardomgevingsvariabelen of toepassingseigenschappen en voorbeeldcode
Verwijs naar de verbindingsgegevens en voorbeeldcode in de volgende tabellen, afhankelijk van het verificatietype en het clienttype van uw verbinding, om rekenservices te verbinden met Azure Database for MySQL. Raadpleeg het artikel Service Connector-internals voor meer informatie over naamconventies.
Door het systeem toegewezen beheerde identiteit
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL-connectionstring |
Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required; |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL-verbindingstring |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username> |
| Toepassingseigenschappen |
Beschrijving |
Voorbeeldwaarde |
spring.datasource.azure.passwordless-enabled |
Verificatie zonder wachtwoord inschakelen |
true |
spring.datasource.url |
URL van Spring Boot JDBC-database |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
Gebruikersnaam van database |
<MySQL-DB-username> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver verbindingsreeks |
<MySQL-DB-username>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
De URL van de databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DBNAME |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_FLAG |
SSL of andere vlaggen |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DATABASE |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_SSLMODE |
SSL-optie |
required |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
Voorbeeldcode
Raadpleeg de stappen en code hieronder om verbinding te maken met Azure Database for MySQL met behulp van een door het systeem toegewezen beheerde identiteit.
Voor .NET is er geen invoegtoepassing of bibliotheek om wachtwoordloze verbindingen te ondersteunen. U kunt een toegangstoken ophalen voor de beheerde identiteit of service-principal met behulp van de clientbibliotheek, zoals Azure.Identity. Vervolgens kunt u het toegangstoken als wachtwoord gebruiken om verbinding te maken met de database. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment voor het verificatietype dat u wilt gebruiken van commentaar ontdoen.
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
Voeg de volgende afhankelijkheden toe aan uw pom.xml-bestand :
<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>
Haal de verbindingsreeks op uit de omgevingsvariabele en voeg de naam van de invoegtoepassing toe om verbinding te maken met de database:
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);
Zie Java en JDBC gebruiken met Azure Database for MySQL - Flexible Server voor meer informatie.
Afhankelijkheden installeren
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
Authenticeer met het toegangstoken dat verkregen is via de azure-identity-bibliotheek en haal verbindingsgegevens op uit de omgevingsvariabele die is ingesteld door de Service Connector. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment ontcommentariëren voor het verificatietype dat u wilt gebruiken.
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()
Installeer afhankelijkheden.
pip install azure-identity
Haal het toegangstoken op via de azure-identity-bibliotheek met omgevingsvariabelen die zijn toegevoegd en gebruikt door de Service Connector. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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')
Bij het instellen van een bestand haalt u azure MySQL-databasegegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Gebruik accessToken verkregen in de vorige stap om toegang te krijgen tot de 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
}
}
Installeer afhankelijkheden.
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"
Haal in code het toegangstoken op via azidentityen maak vervolgens verbinding met Azure MySQL met het token. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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)
}
Afhankelijkheden installeren
npm install --save @azure/identity
npm install --save mysql2
Haal toegangstokens op met behulp van @azure/identity en Azure MySQL-databasegegevens uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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');
});
Zie Verbinding maken met Azure-databases vanuit App Service zonder geheimen met behulp van een beheerde identiteit voor meer codevoorbeelden.
Door de gebruiker toegewezen beheerde identiteit
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CLIENTID |
Uw klantnummer |
<identity-client-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL-verbindingsreeks |
Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required; |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CLIENTID |
Uw cliënt-ID |
<identity-client-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL-verbindingstekenreeks |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username> |
| Toepassingseigenschappen |
Beschrijving |
Voorbeeldwaarde |
spring.datasource.azure.passwordless-enabled |
Verificatie zonder wachtwoord inschakelen |
true |
spring.cloud.azure.credential.client-id |
Uw klant-ID |
<identity-client-ID> |
spring.cloud.azure.credential.client-managed-identity-enabled |
Client beheerde identiteit inschakelen |
true |
spring.datasource.url |
Database URL |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
Gebruikersnaam van database |
username |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
identity-client-ID |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van de databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
Uw client-ID |
<identity-client-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CLIENTID |
Uw client-ID |
<identity-client-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver verbindingsreeks |
<MySQL-DB-username>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
URL van de databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
AZURE_MYSQL_CLIENTID |
Uw Client-ID |
<identity-client-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DBNAME |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_FLAG |
SSL of andere vlaggen |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<identity-client-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DATABASE |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_SSLMODE |
SSL-optie |
required |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<identity-client-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<identity-client-ID> |
Voorbeeldcode
Raadpleeg de stappen en code hieronder om verbinding te maken met Azure Database for MySQL met behulp van een door de gebruiker toegewezen beheerde identiteit.
Voor .NET is er geen invoegtoepassing of bibliotheek om wachtwoordloze verbindingen te ondersteunen. U kunt een toegangstoken ophalen voor de beheerde identiteit of service-principal met behulp van de clientbibliotheek, zoals Azure.Identity. Vervolgens kunt u het toegangstoken als wachtwoord gebruiken om verbinding te maken met de database. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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
Voeg de volgende afhankelijkheden toe aan uw pom.xml-bestand :
<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>
Haal de verbindingsreeks op uit de omgevingsvariabele en voeg de naam van de invoegtoepassing toe om verbinding te maken met de database:
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);
Zie Java en JDBC gebruiken met Azure Database for MySQL - Flexible Server voor meer informatie.
Afhankelijkheden installeren
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
Authenticeren met toegangstoken verkregen via azure-identity bibliotheek en verbindingsinformatie ophalen uit de omgevingsvariabele die is toegevoegd door Service Connector. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment de-commentariëren voor het verificatietype dat u wilt gebruiken.
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()
Installeer afhankelijkheden.
pip install azure-identity
Haal het toegangstoken op via de azure-identity bibliotheek met de omgevingsvariabelen die zijn toegevoegd door Service Connector. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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')
Bij het instellen van een bestand haalt u azure MySQL-databasegegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Gebruik accessToken verkregen in de vorige stap om toegang te krijgen tot de 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
}
}
Installeer afhankelijkheden.
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"
Haal in code het toegangstoken op via azidentityen maak vervolgens verbinding met Azure MySQL met het token. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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)
}
Afhankelijkheden installeren
npm install --save @azure/identity
npm install --save mysql2
Haal toegangstokens op met behulp van @azure/identity en Azure MySQL-databasegegevens uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Wanneer u de onderstaande code gebruikt, haal dan de opmerkingen weg van het deel van het codefragment voor het verificatietype dat u wilt gebruiken.
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');
});
Zie Verbinding maken met Azure-databases vanuit App Service zonder geheimen met behulp van een beheerde identiteit voor meer codevoorbeelden.
Verbindingstekst
Waarschuwing
Microsoft raadt u aan de veiligste verificatiestroom te gebruiken die beschikbaar is. De verificatiestroom die in deze procedure wordt beschreven, vereist een zeer hoge mate van vertrouwen in de toepassing en brengt risico's met zich mee die niet aanwezig zijn in andere stromen. U moet deze stroom alleen gebruiken wanneer andere veiligere stromen, zoals beheerde identiteiten, niet haalbaar zijn.
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL-verbindingsreeks |
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 |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL connection string |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username>&password=<Uri.EscapeDataString(<MySQL-DB-password>) |
| Toepassingseigenschappen |
Beschrijving |
Voorbeeldwaarde |
spring.datasource.url |
URL van Spring Boot JDBC-database |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
Gebruikersnaam van database |
<MySQL-DB-username> |
spring.datasource.password |
Databasewachtwoord |
MySQL-DB-password |
Nadat u een verbinding met het springboot clienttype hebt gemaakt, voegt de Service Connector-service automatisch eigenschappen spring.datasource.urltoe , spring.datasource.username. spring.datasource.password De Spring Boot-toepassing kan dus automatisch bonen toevoegen.
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_PASSWORD |
Databasewachtwoord |
MySQL-DB-password |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_PASSWORD |
Databasewachtwoord |
MySQL-DB-password |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver verbindingsreeks |
<MySQL-DB-username>:<MySQL-DB-password>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_PASSWORD |
Databasewachtwoord |
MySQL-DB-password |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DBNAME |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_FLAG |
SSL of andere vlaggen |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username> |
AZURE_MYSQL_PASSWORD |
Databasewachtwoord |
<MySQL-DB-password> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DATABASE |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_PASSWORD |
Databasewachtwoord |
<MySQL-DB-password> |
AZURE_MYSQL_SSLMODE |
SSL-optie |
required |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
De URL van de databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_PASSWORD |
Databasewachtwoord |
MySQL-DB-password |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
Voorbeeldcode
Raadpleeg de stappen en code hieronder om verbinding te maken met Azure Database for MySQL met behulp van een verbindingsreeks.
- Installeer afhankelijkheden. Volg de richtlijnen voor het installeren van connector/NET MySQL
- Haal in code MySQL-verbindingsreeks op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
using System;
using System.Data;
using MySql.Data.MySqlClient;
string connectionString = Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING");
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
}
- Installeer afhankelijkheden. Volg de richtlijnen voor het installeren van Connector/J.
- Haal in code MySQL-verbindingsreeks op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
String connectionString = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
try (Connection connection = DriverManager.getConnection(connectionString)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
e.printStackTrace();
}
- Installeer afhankelijkheden. Voeg de volgende afhankelijkheden toe aan uw
pom.xml bestand.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-dependencies</artifactId>
<version>5.20.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-starter-jdbc-mysql</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
- De normale Spring App-toepassing instellen, meer details in deze sectie. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
- Installeer afhankelijkheden. Volg de richtlijnen voor het installeren van Connector/Python.
- Haal in code MySQL-verbindingsgegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
import os
import mysql.connector
host = os.getenv('AZURE_MYSQL_HOST')
user = os.getenv('AZURE_MYSQL_USER')
password = os.getenv('AZURE_MYSQL_PASSWORD')
database = os.getenv('Azure_MYSQL_NAME')
cnx = mysql.connector.connect(user=user, password=password,
host=host,
database=database)
cnx.close()
- Installeer afhankelijkheden.
pip install django
- Haal bij het instellen van het bestand MySQL-databasegegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
user = os.getenv('AZURE_MYSQL_USER')
password = os.getenv('AZURE_MYSQL_PASSWORD')
database = os.getenv('AZURE_MYSQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
- Installeer afhankelijkheden.
go get -u github.com/go-sql-driver/mysql
- Haal in code MySQL-verbindingsreeks op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
import (
"database/sql"
"fmt"
"os"
_ "github.com/go-sql-driver/mysql"
)
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING")
db, err := sql.Open("mysql", connectionString)
- Installeer afhankelijkheden.
npm install mysql2
- Haal in code MySQL-verbindingsgegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
const mysql = require('mysql2')
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: process.env.AZURE_MYSQL_PASSWORD,
database: process.env.AZURE_MYSQL_DATABASE,
port: Number(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.');
});
- Installeer afhankelijkheden. Volg de handleiding om MySQLi te installeren.
- Haal in code MySQL-verbindingsgegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
<?php
$host = getenv('AZURE_MYSQL_HOST');
$username = getenv('AZURE_MYSQL_USER');
$password = getenv('AZURE_MYSQL_PASSWORD');
$database = getenv('Azure_MYSQL_DBNAME');
$port = int(getenv('AZURE_MYSQL_PORT'));
# $flag = getenv('AZURE_MYSQL_FLAG');
$conn = mysqli_init();
# mysqli_ssl_set($conn,NULL,NULL,NULL,NULL,NULL);
mysqli_real_connect($conn, $host, $username, $password, $database, $port, NULL);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: ' . mysqli_connect_error());
}
echo 'Connected successfully to MySQL database!';
mysqli_close($conn);
?>
- Installeer afhankelijkheden.
gem install mysql2
- Haal in code MySQL-verbindingsgegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Raadpleeg deze stappen om een versleutelde verbinding tot stand te brengen met mySQL-server via SSL.
require 'mysql2'
require 'dotenv/load'
client = Mysql2::Client.new(
host: ENV['AZURE_MYSQL_HOST'],
username: ENV['AZURE_MYSQL_USERNAME'],
password: ENV['AZURE_MYSQL_PASSWORD'],
database: ENV['AZURE_MYSQL_DATABASE'],
# sslca: ca_path
)
client.close
Service-principal
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CLIENTID |
Uw klant-id |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw clientgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw huurder-ID |
<tenant-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL-verbindingsreeks |
Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw clientgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw tenant-ID |
<tenant-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL-verbindingstekenreeks |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username> |
| Toepassingseigenschappen |
Beschrijving |
Voorbeeldwaarde |
spring.datasource.azure.passwordless-enabled |
Verificatie zonder wachtwoord inschakelen |
true |
spring.cloud.azure.credential.client-id |
Uw klantnummer |
<client-ID> |
spring.cloud.azure.credential.client-secret |
Uw cliëntgeheim |
<client-secret> |
spring.cloud.azure.credential.tenant-id |
Uw tenant-ID |
<tenant-ID> |
spring.datasource.url |
Database URL |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
Gebruikersnaam van database |
username |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van de databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
Uw client-ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw cliëntsleutel |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw tenant-ID |
<tenant-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_NAME |
Databasenaam |
MySQL-DB-name |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw cliëntgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw tenant-ID |
<tenant-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw clientgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw huurders-ID |
<tenant-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver verbindingsreeks |
<MySQL-DB-username>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
De URL van de databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
AZURE_MYSQL_CLIENTID |
Uw cliënt ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw cliëntgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw tenant-ID |
<tenant-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DBNAME |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van de databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_FLAG |
SSL of andere vlaggen |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw clientgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw huurders-ID |
<tenant-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_DATABASE |
Databasenaam |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
URL van databasehost |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_SSLMODE |
SSL-optie |
required |
AZURE_MYSQL_CLIENTID |
Uw klant-ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw cliëntgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw huurders-id |
<tenant-ID> |
| Naam van standaardomgevingsvariabele |
Beschrijving |
Voorbeeldwaarde |
AZURE_MYSQL_HOST |
URL van de database-host |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
Gebruikersnaam van database |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
Databasenaam |
<database-name> |
AZURE_MYSQL_PORT |
Poortnummer |
3306 |
AZURE_MYSQL_SSL |
SSL-optie |
true |
AZURE_MYSQL_CLIENTID |
Uw klant-id |
<identity-client-ID> |
AZURE_MYSQL_CLIENTSECRET |
Uw cliëntgeheim |
<client-secret> |
AZURE_MYSQL_TENANTID |
Uw tenant-ID |
<tenant-ID> |
Voorbeeldcode
Raadpleeg de stappen en code hieronder om verbinding te maken met Azure Database for MySQL met behulp van een service-principal.
Voor .NET is er geen invoegtoepassing of bibliotheek om wachtwoordloze verbindingen te ondersteunen. U kunt een toegangstoken ophalen voor de beheerde identiteit of service-principal met behulp van de clientbibliotheek, zoals Azure.Identity. Vervolgens kunt u het toegangstoken als wachtwoord gebruiken om verbinding te maken met de database. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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
Voeg de volgende afhankelijkheden toe aan uw pom.xml-bestand :
<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>
Haal de verbindingsreeks op uit de omgevingsvariabele en voeg de naam van de invoegtoepassing toe om verbinding te maken met de database:
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);
Zie Java en JDBC gebruiken met Azure Database for MySQL - Flexible Server voor meer informatie.
Afhankelijkheden installeren
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
Authenticatie met toegangstoken verkrijgen via de azure-identity-bibliotheek en netwerkverbindingsinformatie ophalen uit de door Service Connector toegevoegde omgevingsvariabele. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment ontcommentariëren voor het verificatietype dat u wilt gebruiken.
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()
Installeer afhankelijkheden.
pip install azure-identity
Haal het toegangstoken op via de azure-identity bibliotheek met de omgevingsvariabelen die zijn toegevoegd door Service Connector. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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')
Bij het instellen van een bestand haalt u azure MySQL-databasegegevens op uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Gebruik accessToken verkregen in de vorige stap om toegang te krijgen tot de 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
}
}
Installeer afhankelijkheden.
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"
Haal in code het toegangstoken op via azidentityen maak vervolgens verbinding met Azure MySQL met het token. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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)
}
Afhankelijkheden installeren
npm install --save @azure/identity
npm install --save mysql2
Haal toegangstokens op met behulp van @azure/identity en Azure MySQL-databasegegevens uit omgevingsvariabelen die zijn toegevoegd door de Service Connector-service. Als u de onderstaande code gebruikt, moet u het gedeelte van het codefragment verwijderen voor het verificatietype dat u wilt gebruiken.
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');
});
Zie Verbinding maken met Azure-databases vanuit App Service zonder geheimen met behulp van een beheerde identiteit voor meer codevoorbeelden.
Volgende stappen
Volg de documentatie voor meer informatie over Service Connector.