Condividi tramite


Integrare Database di Azure per PostgreSQL con Service Connessione or

Questa pagina mostra i metodi e i client di autenticazione supportati e mostra il codice di esempio che è possibile usare per connettersi Database di Azure per PostgreSQL ad altri servizi cloud tramite Service Connessione or. È comunque possibile connettersi a Database di Azure per PostgreSQL in altri linguaggi di programmazione senza usare Service Connessione or. Questa pagina mostra anche i nomi e i valori predefiniti delle variabili di ambiente (o configurazione spring boot) che si ottengono quando si crea la connessione al servizio.

Servizi di calcolo supportati

Il Connessione or del servizio può essere usato per connettere i servizi di calcolo seguenti a Database di Azure per PostgreSQL:

  • Servizio app di Azure
  • Funzioni di Azure
  • Configurazione app di Azure
  • 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 del servizio di calcolo a Database di Azure per PostgreSQL tramite Service Connessione or. 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 Segreto/stringa di connessione Entità servizio
.NET
Go (pg)
Java (JDBC)
Java - Spring Boot (JDBC)
Node.js (pg)
PHP (nativo)
Python (psycopg2)
Python-Django
Ruby (ruby-pg)
Nessuno

Questa tabella indica che tutte le combinazioni di tipi client e metodi di autenticazione nella tabella sono supportate. Tutti i tipi di client possono usare uno dei metodi di autenticazione per connettersi a Database di Azure per PostgreSQL tramite Service Connessione or.

Nota

L'identità gestita assegnata dal sistema, l'identità gestita assegnata dall'utente e l'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 PostgreSQL. Per altre informazioni sulle convenzioni di denominazione, vedere l'articolo Servizi Connessione or internals .

Identità gestita assegnata dal sistema

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL stringa di connessione Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

Codice di esempio

Fare riferimento ai passaggi e al codice seguenti per connettersi a Database di Azure per PostgreSQL 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 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();
}

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

Identità gestita assegnata dall'utente

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_POSTGRESQL_CLIENTID Your client ID <identity-client-ID>
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL stringa di connessione Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

Codice di esempio

Fare riferimento ai passaggi e al codice seguenti per connettersi a Database di Azure per PostgreSQL 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 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();
}

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

Stringa di connessione

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL stringa di connessione Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

Codice di esempio

Fare riferimento alla procedura e al codice seguente per connettersi a Database di Azure per PostgreSQL usando un stringa di connessione.

  1. Installare le dipendenze. Seguire le indicazioni per installare Npgsql
  2. Nel codice ottenere il stringa di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio service Connessione or. Per impostare le configurazioni TSL per il server PostgreSQL, vedere questi passaggi.
    using System;
    using Npgsql;
    
    string connectionString = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING");
    using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
    {
        connection.Open();
    }
    

Entità servizio

Nome variabile di ambiente predefinito Descrizione Valore di esempio
AZURE_POSTGRESQL_CLIENTID Your client ID <client-ID>
AZURE_POSTGRESQL_CLIENTSECRET Segreto client <client-secret>
AZURE_POSTGRESQL_TENANTID ID del tenant. <tenant-ID>
AZURE_POSTGRESQL_CONNECTIONSTRING .NET PostgreSQL stringa di connessione Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>;

Codice di esempio

Fare riferimento alla procedura e al codice seguente per connettersi a Database di Azure per PostgreSQL usando un'entità servizio.

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();
}

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

Passaggi successivi

Seguire le esercitazioni elencate di seguito per altre informazioni su Service Connessione or.