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 PostgreSQL usando 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.
Servizi di calcolo supportati
Connettore di servizi può essere usato per connettere i servizi di calcolo seguenti a Database di Azure per PostgreSQL:
- Servizio app di Azure
- App contenitore di Azure
- Funzioni di Azure
- Servizio Azure Kubernetes (AKS)
- App Spring di Azure
Tipi di autenticazione e 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 PostgreSQL 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 di segreto/connessione |
Entità servizio |
.RETE |
Sì |
Sì |
Sì |
Sì |
Go (Per Tutti) |
Sì |
Sì |
Sì |
Sì |
Java (JDBC) |
Sì |
Sì |
Sì |
Sì |
Java - Spring Boot (JDBC) |
Sì |
Sì |
Sì |
Sì |
Node.js (pg) |
Sì |
Sì |
Sì |
Sì |
PHP (nativo) |
Sì |
Sì |
Sì |
Sì |
Python (psycopg2) |
Sì |
Sì |
Sì |
Sì |
Python-Django |
Sì |
Sì |
Sì |
Sì |
Ruby (ruby-pg) |
Sì |
Sì |
Sì |
Sì |
Nessuno |
Sì |
Sì |
Sì |
Sì |
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 altre informazioni sulle convenzioni di denominazione, vedere l'articolo Elementi interni di Service Connector .
Identità gestita assegnata dal sistema
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL .NET |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL JDBC |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username> |
Proprietà dell'applicazione |
Descrizione |
Valore di esempio |
spring.datasource.azure.passwordless-enabled |
Abilitare l'autenticazione senza password |
true |
spring.datasource.url |
URL database |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
Nome utente database |
username |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione psycopg2 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_NAME |
Nome database |
<database-name> |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Go |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL PHP nativa |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Ruby |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
Nome utente database |
<username> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
Codice di esempio
Per connettersi a Database di Azure per PostgreSQL tramite un'identità gestita assegnata dal sistema, fare riferimento alla procedura 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 per l'entità servizio usando una 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 corresponding to the authentication type you want to use.
// 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 :
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.5</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
Ottenere la stringa di connessione dalle variabili di ambiente e aggiungere il nome del plug-in per connettersi al database:
import java.sql.*;
String url = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&authenticationPluginClassName=" + pluginName);
Per ulteriori informazioni, vedi le seguenti risorse:
Installare le dipendenze.
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
Ottenere il token di accesso tramite la libreria azure-identity
e usare il token come password. Ottenere informazioni di connessione dalle variabili di ambiente aggiunte da Connettore di servizi. 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 corresponding to the authentication type you want to use.
# 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 tramite la libreria azure-identity
usando le variabili di ambiente aggiunte da Connettore di servizi. 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 corresponding to the authentication type you want to use.
# 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 delle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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 tramite azidentity
, quindi usarlo come password per connettersi a PostgreSQL di Azure insieme alle informazioni di connessione fornite da Connettore di servizi. 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 corresponding to the authentication type you want to use.
// 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()
Installare le dipendenze.
npm install --save @azure/identity
npm install --save pg
Nel codice, ottenere il token di accesso tramite @azure/identity
e le informazioni sulla connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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";
import { Client } from 'pg';
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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;
// const credential = new ClientSecretCredential(tenantId, clientId, 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 tramite l'API REST di Azure.
Nel codice, ottenere il token di accesso tramite l'API REST con la libreria preferita.
Per l'identità assegnata dall'utente e l'identità assegnata dal sistema, Servizio app e App contenitore forniscono un endpoint REST accessibile internamente in modo da 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 usare https://ossrdbms-aad.database.windows.net
come resource
nella query. Per l'identità assegnata dall'utente, includere anche l'ID client delle variabili di ambiente aggiunte da Connettore di servizi nella query.
Per ottenere il token di accesso, fare riferimento alla richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare i dettagli su come acquisire il token. Effettuare la richiesta POST nell’ambito di https://ossrdbms-aad.database.windows.net/.default
e con l'ID tenant, l'ID client e il segreto client dell'entità servizio delle variabili di ambiente aggiunte da Connettore di servizi.
Combinare il token di accesso e la stringa di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Service Connector per stabilire la connessione.
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
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 tramite l'API REST di Azure.
Installare le dipendenze.
gem install pg
Nel codice, ottenere il token di accesso tramite l’API REST e le informazioni sulla connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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.
Servizio app e App 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 corresponding to the authentication type you want to use.
# 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 ulteriori dettagli su come acquisire il token di accesso per il principale del servizio.
Successivamente, se si sono create tabelle e sequenze nel server flessibile PostgreSQL prima di usare Connettore di servizi, è necessario connettersi come proprietario e concedere l'autorizzazione alle <aad-username>
create da Connettore di servizi. Il nome utente della stringa di connessione o della configurazione impostata da Connettore di servizi dovrebbe essere simile a aad_<connection name>
. Se si usa il portale di Azure, selezionare il pulsante Espandi accanto alla colonna Service Type
e ottenere il valore. Se si usa l'interfaccia della riga di comando di Azure, controllare configurations
nell'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>
sono i proprietari della tabella esistente che può concedere autorizzazioni ad altri utenti.
<aad-username>
è l'utente creato da Connettore di servizi. Sostituirlo con il valore effettivo.
Convalidare il risultato tramite 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 |
L’ID client |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL .NET |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL JDBC |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username> |
Proprietà dell'applicazione |
Descrizione |
Valore di esempio |
spring.datasource.azure.passwordless-enabled |
Abilitare l'autenticazione senza password |
true |
spring.cloud.azure.credential.client-id |
L’ID client |
<identity-client-ID> |
spring.cloud.azure.credential.client-managed-identity-enabled |
Abilitare l'identità gestita del client |
true |
spring.datasource.url |
URL database |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
Nome utente database |
username |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione psycopg2 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_NAME |
Nome database |
<database-name> |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<<identity-client-ID>> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Go |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL PHP nativa |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Ruby |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
Nome utente database |
<username> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
Codice di esempio
Fare riferimento alla procedura e al codice seguenti per connettersi a Database di Azure per PostgreSQL tramite 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 per l'entità servizio usando una 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 corresponding to the authentication type you want to use.
// 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 :
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.5</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
Ottenere la stringa di connessione dalle variabili di ambiente e aggiungere il nome del plug-in per connettersi al database:
import java.sql.*;
String url = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&authenticationPluginClassName=" + pluginName);
Per ulteriori informazioni, vedi le seguenti risorse:
Installare le dipendenze.
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
Ottenere il token di accesso tramite la libreria azure-identity
e usare il token come password. Ottenere informazioni di connessione dalle variabili di ambiente aggiunte da Connettore di servizi. 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 corresponding to the authentication type you want to use.
# 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 tramite la libreria azure-identity
usando le variabili di ambiente aggiunte da Connettore di servizi. 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 corresponding to the authentication type you want to use.
# 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 delle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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 tramite azidentity
, quindi usarlo come password per connettersi a PostgreSQL di Azure insieme alle informazioni di connessione fornite da Connettore di servizi. 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 corresponding to the authentication type you want to use.
// 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()
Installare le dipendenze.
npm install --save @azure/identity
npm install --save pg
Nel codice, ottenere il token di accesso tramite @azure/identity
e le informazioni sulla connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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";
import { Client } from 'pg';
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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;
// const credential = new ClientSecretCredential(tenantId, clientId, 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 tramite l'API REST di Azure.
Nel codice, ottenere il token di accesso tramite l'API REST con la libreria preferita.
Per l'identità assegnata dall'utente e l'identità assegnata dal sistema, Servizio app e App contenitore forniscono un endpoint REST accessibile internamente in modo da 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 usare https://ossrdbms-aad.database.windows.net
come resource
nella query. Per l'identità assegnata dall'utente, includere anche l'ID client delle variabili di ambiente aggiunte da Connettore di servizi nella query.
Per ottenere il token di accesso, fare riferimento alla richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare i dettagli su come acquisire il token. Effettuare la richiesta POST nell’ambito di https://ossrdbms-aad.database.windows.net/.default
e con l'ID tenant, l'ID client e il segreto client dell'entità servizio delle variabili di ambiente aggiunte da Connettore di servizi.
Combinare il token di accesso e la stringa di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Service Connector per stabilire la connessione.
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
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 tramite l'API REST di Azure.
Installare le dipendenze.
gem install pg
Nel codice, ottenere il token di accesso tramite l’API REST e le informazioni sulla connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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.
Servizio app e App 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 corresponding to the authentication type you want to use.
# 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 ulteriori dettagli su come acquisire il token di accesso per il principale del servizio.
Successivamente, se si sono create tabelle e sequenze nel server flessibile PostgreSQL prima di usare Connettore di servizi, è necessario connettersi come proprietario e concedere l'autorizzazione alle <aad-username>
create da Connettore di servizi. Il nome utente della stringa di connessione o della configurazione impostata da Connettore di servizi dovrebbe essere simile a aad_<connection name>
. Se si usa il portale di Azure, selezionare il pulsante Espandi accanto alla colonna Service Type
e ottenere il valore. Se si usa l'interfaccia della riga di comando di Azure, controllare configurations
nell'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>
sono i proprietari della tabella esistente che può concedere autorizzazioni ad altri utenti.
<aad-username>
è l'utente creato da Connettore di servizi. Sostituirlo con il valore effettivo.
Convalidare il risultato tramite 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
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_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL .NET |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL JDBC |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username>&password=<password> |
Proprietà dell'applicazione |
Descrizione |
Valore di esempio |
spring.datasource.url |
URL database |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
Nome utente database |
<username> |
spring.datasource.password |
Password database |
<password> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione psycopg2 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> password=<password> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_NAME |
Nome database |
<database-name> |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
AZURE_POSTGRESQL_PASSWORD |
Password database |
<database-password> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Go |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> password=<password> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
AZURE_POSTGRESQL_PASSWORD |
Password database |
<password> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL PHP nativa |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> password=<password> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Ruby |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> password=<password> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
Nome utente database |
<username> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
AZURE_POSTGRESQL_PASSWORD |
Password database |
<password> |
Codice di esempio
Fare riferimento alla procedura e al codice seguenti per connettersi a Database di Azure per PostgreSQL tramite una stringa di connessione.
- Installare le dipendenze seguendo le indicazioni di Npgsql
- Nel codice ottenere la stringa di connessione PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
using System;
using Npgsql;
string connectionString = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING");
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
}
- Installare le dipendenze seguendo le indicazioni del pgJDBC.
- Nel codice ottenere la stringa di connessione PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
String connectionString = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionString);
System.out.println("Connection successful!");
} catch (SQLException e){
System.out.println(e.getMessage());
}
- Installare il modulo Spring Cloud Azure Starter JDBC PostgreSQL aggiungendo le dipendenze seguenti al file
pom.xml
. Trovare la versione di Spring Cloud Azure qui.
<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-postgresql</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
- Configurare un'applicazione Spring Boot, altri dettagli in questa sezione.
- Installare le dipendenze seguendo le indicazioni di psycopg2.
- Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
import os
import psycopg2
connection_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
connection = psycopg2.connect(connection_string)
print("Connection established")
connection.close()
- Installare le dipendenze seguendo le indicazioni su Django e le indicazioni su psycopg2.
pip install django
pip install psycopg2
- Nel file di impostazione ottenere le informazioni sul database PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
# in your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = os.getenv('AZURE_POSTGRESQL_PASSWORD')
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
- Nel codice ottenere la stringa di connessione PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
import (
"database/sql"
"fmt"
"os"
_ "github.com/lib/pq"
)
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING")
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
- Installare le dipendenze.
npm install pg dotenv
- Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
import { Client } from 'pg';
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: process.env.AZURE_POSTGRESQL_PASSWORD,
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();
})();
- Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
<?php
$conn_string = getenv('AZURE_POSTGRESQL_CONNECTIONSTRING');
$dbconn = pg_connect($conn_string);
?>
- Installare le dipendenze.
gem install pg
- Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte da Service Connector.
require 'pg'
require 'dotenv/load'
begin
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'],
)
rescue PG::Error => e
puts e.message
ensure
connection.close if connection
end
Entità servizio
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL .NET |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL JDBC |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username> |
Proprietà dell'applicazione |
Descrizione |
Valore di esempio |
spring.datasource.azure.passwordless-enabled |
Abilitare l'autenticazione senza password |
true |
spring.cloud.azure.credential.client-id |
L’ID client |
<client-ID> |
spring.cloud.azure.credential.client-secret |
Segreto client |
<client-secret> |
spring.cloud.azure.credential.tenant-id |
ID del tenant. |
<tenant-ID> |
spring.datasource.url |
URL database |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
Nome utente database |
username |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione psycopg2 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_NAME |
Nome database |
<database-name> |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Client SECRET |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Go |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
Nome utente database |
<username> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL PHP nativa |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Stringa di connessione PostgreSQL Ruby |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
Nome variabile di ambiente predefinito |
Descrizione |
Valore di esempio |
AZURE_POSTGRESQL_HOST |
URL host del database |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
Nome utente database |
<username> |
AZURE_POSTGRESQL_DATABASE |
Nome database |
<database-name> |
AZURE_POSTGRESQL_PORT |
Numero di porta |
5432 |
AZURE_POSTGRESQL_SSL |
Opzione SSL |
true |
AZURE_POSTGRESQL_CLIENTID |
L’ID client |
<identity-client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
Segreto client |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
ID del tenant. |
<tenant-ID> |
Codice di esempio
Per connettersi a Database di Azure per PostgreSQL tramite un'entità servizio, fare riferimento alla procedura 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 per l'entità servizio usando una 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 corresponding to the authentication type you want to use.
// 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 :
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.5</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
Ottenere la stringa di connessione dalle variabili di ambiente e aggiungere il nome del plug-in per connettersi al database:
import java.sql.*;
String url = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&authenticationPluginClassName=" + pluginName);
Per ulteriori informazioni, vedi le seguenti risorse:
Installare le dipendenze.
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
Ottenere il token di accesso tramite la libreria azure-identity
e usare il token come password. Ottenere informazioni di connessione dalle variabili di ambiente aggiunte da Connettore di servizi. 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 corresponding to the authentication type you want to use.
# 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 tramite la libreria azure-identity
usando le variabili di ambiente aggiunte da Connettore di servizi. 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 corresponding to the authentication type you want to use.
# 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 delle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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 tramite azidentity
, quindi usarlo come password per connettersi a PostgreSQL di Azure insieme alle informazioni di connessione fornite da Connettore di servizi. 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 corresponding to the authentication type you want to use.
// 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()
Installare le dipendenze.
npm install --save @azure/identity
npm install --save pg
Nel codice, ottenere il token di accesso tramite @azure/identity
e le informazioni sulla connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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";
import { Client } from 'pg';
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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;
// const credential = new ClientSecretCredential(tenantId, clientId, 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 tramite l'API REST di Azure.
Nel codice, ottenere il token di accesso tramite l'API REST con la libreria preferita.
Per l'identità assegnata dall'utente e l'identità assegnata dal sistema, Servizio app e App contenitore forniscono un endpoint REST accessibile internamente in modo da 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 usare https://ossrdbms-aad.database.windows.net
come resource
nella query. Per l'identità assegnata dall'utente, includere anche l'ID client delle variabili di ambiente aggiunte da Connettore di servizi nella query.
Per ottenere il token di accesso, fare riferimento alla richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare i dettagli su come acquisire il token. Effettuare la richiesta POST nell’ambito di https://ossrdbms-aad.database.windows.net/.default
e con l'ID tenant, l'ID client e il segreto client dell'entità servizio delle variabili di ambiente aggiunte da Connettore di servizi.
Combinare il token di accesso e la stringa di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Service Connector per stabilire la connessione.
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
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 tramite l'API REST di Azure.
Installare le dipendenze.
gem install pg
Nel codice, ottenere il token di accesso tramite l’API REST e le informazioni sulla connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connettore di servizi. 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.
Servizio app e App 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 corresponding to the authentication type you want to use.
# 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 ulteriori dettagli su come acquisire il token di accesso per il principale del servizio.
Successivamente, se si sono create tabelle e sequenze nel server flessibile PostgreSQL prima di usare Connettore di servizi, è necessario connettersi come proprietario e concedere l'autorizzazione alle <aad-username>
create da Connettore di servizi. Il nome utente della stringa di connessione o della configurazione impostata da Connettore di servizi dovrebbe essere simile a aad_<connection name>
. Se si usa il portale di Azure, selezionare il pulsante Espandi accanto alla colonna Service Type
e ottenere il valore. Se si usa l'interfaccia della riga di comando di Azure, controllare configurations
nell'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>
sono i proprietari della tabella esistente che può concedere autorizzazioni ad altri utenti.
<aad-username>
è l'utente creato da Connettore di servizi. Sostituirlo con il valore effettivo.
Convalidare il risultato tramite 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
Per altre informazioni sul connettore di servizi seguire le esercitazioni riportate di seguito.