Integrare Database di Azure per PostgreSQL con Service Connessione or
Articolo
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
Sì
Sì
Sì
Sì
Go (pg)
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ì
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 .
Per .NET non è disponibile un plug-in o una libreria per supportare connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
using Azure.Identity;
using Azure.Core;
using Npgsql;
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.windows.net/.default"
}));
// Combine the token with the connection string from the environment variables provided by Service Connector.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING")};Password={accessToken.Token}";
// Establish the connection.
using (var connection = new NpgsqlConnection(connectionString))
{
Console.WriteLine("Opening connection using access token...");
connection.Open();
}
Aggiungere le dipendenze seguenti nel file pom.xml :
Per un'applicazione Spring, se si crea una connessione con l'opzione --client-type springboot, Service Connessione or imposta le proprietà spring.datasource.azure.passwordless-enabled, spring.datasource.urle spring.datasource.username su Azure Spring Apps.
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
Ottenere il token di accesso usando azure-identity la libreria e usare il token come password. Ottenere informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
conn_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
conn = psycopg2.connect(conn_string + ' password=' + accessToken.token)
Installare le dipendenze.
pip install azure-identity
Ottenere il token di accesso usando la azure-identity libreria usando le variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
Nel file di impostazione ottenere informazioni sul database PostgreSQL di Azure dalle variabili di ambiente aggiunte dal servizio Connessione or. Usare accessToken acquisito nel passaggio precedente per accedere al database.
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
Installare le dipendenze.
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
Nel codice ottenere il token di accesso usando azidentity, quindi usarlo come password per connettersi ad Azure PostgreSQL insieme alle informazioni di connessione fornite da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
// Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
Nel codice ottenere il token di accesso usando @azure/identity e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio service Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
// Use the token and the connection information from the environment variables added by Service Connector to establish the connection.
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: accesstoken.token,
database: process.env.AZURE_POSTGRESQL_DATABASE,
port: Number(process.env.AZURE_POSTGRESQL_PORT) ,
ssl: process.env.AZURE_POSTGRESQL_SSL
});
await client.connect();
await client.end();
})();
Per PHP, non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Nel codice ottenere il token di accesso usando l'API REST con la libreria preferita.
Per l'identità assegnata dall'utente e l'identità assegnata dal sistema, servizio app e App contenitore fornisce un endpoint REST accessibile internamente per recuperare i token per le identità gestite definendo due variabili di ambiente: IDENTITY_ENDPOINT e IDENTITY_HEADER. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
Ottenere il token di accesso effettuando una richiesta HTTP GET all'endpoint di identità e usarlo https://ossrdbms-aad.database.windows.net come resource nella query. Per l'identità assegnata dall'utente, includere anche l'ID client dalle variabili di ambiente aggiunte da Service Connessione or nella query.
Per l'entità servizio, vedere la richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare i dettagli su come acquisire il token di accesso. Effettuare la richiesta POST per l'ambito di https://ossrdbms-aad.database.windows.net/.default e con l'ID tenant, l'ID client e il segreto client dell'entità servizio dalle variabili di ambiente aggiunte da Service Connessione or.
Combinare il token di accesso e l'sting della connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or per stabilire la connessione.
Per Ruby non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Installare le dipendenze.
gem install pg
Nel codice ottenere il token di accesso usando l'API REST e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Il servizio app e le app del contenitore forniscono un endpoint REST accessibile internamente per recuperare i token per le identità gestite. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client-id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
Fare riferimento alla richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare altri dettagli su come acquisire il token di accesso per l'entità servizio.
Per altre lingue, usare le proprietà di connessione impostate da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per PostgreSQL con Service Connessione or.
Successivamente, se sono state create tabelle e sequenze nel server flessibile PostgreSQL prima di usare Service Connessione or, è necessario connettersi come proprietario e concedere l'autorizzazione a <aad-username> creata da Service Connessione or. Il nome utente del stringa di connessione o della configurazione impostato da Service Connessione or dovrebbe essere simile aad_<connection name>a . Se si usa il portale di Azure, selezionare il pulsante di espansione accanto alla Service Type colonna e ottenere il valore. Se si usa l'interfaccia della riga di comando di Azure, archiviare configurations l'output del comando dell'interfaccia della riga di comando.
Eseguire quindi la query per concedere l'autorizzazione
az extension add --name rdbms-connect
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \"<aad-username>\";GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO \"<aad username>\";"
<owner-username> e <owner-password> è il proprietario della tabella esistente che può concedere autorizzazioni ad altri utenti. <aad-username>è l'utente creato da Service Connessione or. Sostituirli con il valore effettivo.
Convalidare il risultato con il comando :
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "SELECT distinct(table_name) FROM information_schema.table_privileges WHERE grantee='<aad-username>' AND table_schema='public';" --output table
Per .NET non è disponibile un plug-in o una libreria per supportare connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
using Azure.Identity;
using Azure.Core;
using Npgsql;
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.windows.net/.default"
}));
// Combine the token with the connection string from the environment variables provided by Service Connector.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING")};Password={accessToken.Token}";
// Establish the connection.
using (var connection = new NpgsqlConnection(connectionString))
{
Console.WriteLine("Opening connection using access token...");
connection.Open();
}
Aggiungere le dipendenze seguenti nel file pom.xml :
Per un'applicazione Spring, se si crea una connessione con l'opzione --client-type springboot, Service Connessione or imposta le proprietà spring.datasource.azure.passwordless-enabled, spring.datasource.urle spring.datasource.username su Azure Spring Apps.
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
Ottenere il token di accesso usando azure-identity la libreria e usare il token come password. Ottenere informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
conn_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
conn = psycopg2.connect(conn_string + ' password=' + accessToken.token)
Installare le dipendenze.
pip install azure-identity
Ottenere il token di accesso usando la azure-identity libreria usando le variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
Nel file di impostazione ottenere informazioni sul database PostgreSQL di Azure dalle variabili di ambiente aggiunte dal servizio Connessione or. Usare accessToken acquisito nel passaggio precedente per accedere al database.
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
Installare le dipendenze.
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
Nel codice ottenere il token di accesso usando azidentity, quindi usarlo come password per connettersi ad Azure PostgreSQL insieme alle informazioni di connessione fornite da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
// Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
Nel codice ottenere il token di accesso usando @azure/identity e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio service Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
// Use the token and the connection information from the environment variables added by Service Connector to establish the connection.
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: accesstoken.token,
database: process.env.AZURE_POSTGRESQL_DATABASE,
port: Number(process.env.AZURE_POSTGRESQL_PORT) ,
ssl: process.env.AZURE_POSTGRESQL_SSL
});
await client.connect();
await client.end();
})();
Per PHP, non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Nel codice ottenere il token di accesso usando l'API REST con la libreria preferita.
Per l'identità assegnata dall'utente e l'identità assegnata dal sistema, servizio app e App contenitore fornisce un endpoint REST accessibile internamente per recuperare i token per le identità gestite definendo due variabili di ambiente: IDENTITY_ENDPOINT e IDENTITY_HEADER. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
Ottenere il token di accesso effettuando una richiesta HTTP GET all'endpoint di identità e usarlo https://ossrdbms-aad.database.windows.net come resource nella query. Per l'identità assegnata dall'utente, includere anche l'ID client dalle variabili di ambiente aggiunte da Service Connessione or nella query.
Per l'entità servizio, vedere la richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare i dettagli su come acquisire il token di accesso. Effettuare la richiesta POST per l'ambito di https://ossrdbms-aad.database.windows.net/.default e con l'ID tenant, l'ID client e il segreto client dell'entità servizio dalle variabili di ambiente aggiunte da Service Connessione or.
Combinare il token di accesso e l'sting della connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or per stabilire la connessione.
Per Ruby non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Installare le dipendenze.
gem install pg
Nel codice ottenere il token di accesso usando l'API REST e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Il servizio app e le app del contenitore forniscono un endpoint REST accessibile internamente per recuperare i token per le identità gestite. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client-id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
Fare riferimento alla richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare altri dettagli su come acquisire il token di accesso per l'entità servizio.
Per altre lingue, usare le proprietà di connessione impostate da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per PostgreSQL con Service Connessione or.
Successivamente, se sono state create tabelle e sequenze nel server flessibile PostgreSQL prima di usare Service Connessione or, è necessario connettersi come proprietario e concedere l'autorizzazione a <aad-username> creata da Service Connessione or. Il nome utente del stringa di connessione o della configurazione impostato da Service Connessione or dovrebbe essere simile aad_<connection name>a . Se si usa il portale di Azure, selezionare il pulsante di espansione accanto alla Service Type colonna e ottenere il valore. Se si usa l'interfaccia della riga di comando di Azure, archiviare configurations l'output del comando dell'interfaccia della riga di comando.
Eseguire quindi la query per concedere l'autorizzazione
az extension add --name rdbms-connect
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \"<aad-username>\";GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO \"<aad username>\";"
<owner-username> e <owner-password> è il proprietario della tabella esistente che può concedere autorizzazioni ad altri utenti. <aad-username>è l'utente creato da Service Connessione or. Sostituirli con il valore effettivo.
Convalidare il risultato con il comando :
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "SELECT distinct(table_name) FROM information_schema.table_privileges WHERE grantee='<aad-username>' AND table_schema='public';" --output table
Installare le dipendenze. Seguire le indicazioni per installare Npgsql
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();
}
Installare le dipendenze. Seguire le indicazioni per installare pgJDBC.
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.
Installare il modulo Spring Cloud Azure Starter JDBC PostgreSQL aggiungendo le dipendenze seguenti al pom.xml file. Trovare la versione di Spring Cloud Azure qui.
Configurare un'applicazione Spring App e altri dettagli in questa sezione. Per impostare le configurazioni TSL per il server PostgreSQL, vedere questi passaggi.
Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or del servizio. Per impostare le configurazioni TSL per il server PostgreSQL, vedere questi passaggi.
Nel file di impostazione ottenere le informazioni sul database PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or. Per impostare le configurazioni TSL per il server PostgreSQL, vedere questi passaggi.
# 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 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.
Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or del servizio. Per impostare le configurazioni TSL per il server PostgreSQL, vedere questi passaggi.
Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or del servizio. Per impostare le configurazioni TSL per il server PostgreSQL, vedere questi passaggi.
Nel codice ottenere le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or del servizio. Per impostare le configurazioni TSL per il server PostgreSQL, vedere questi passaggi.
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
Per altre lingue, usare le proprietà di connessione impostate da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per PostgreSQL con Service Connessione or.
Per .NET non è disponibile un plug-in o una libreria per supportare connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client come Azure.Identity. È quindi possibile usare il token di accesso come password per connettersi al database. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
using Azure.Identity;
using Azure.Core;
using Npgsql;
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.windows.net/.default"
}));
// Combine the token with the connection string from the environment variables provided by Service Connector.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING")};Password={accessToken.Token}";
// Establish the connection.
using (var connection = new NpgsqlConnection(connectionString))
{
Console.WriteLine("Opening connection using access token...");
connection.Open();
}
Aggiungere le dipendenze seguenti nel file pom.xml :
Per un'applicazione Spring, se si crea una connessione con l'opzione --client-type springboot, Service Connessione or imposta le proprietà spring.datasource.azure.passwordless-enabled, spring.datasource.urle spring.datasource.username su Azure Spring Apps.
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
Ottenere il token di accesso usando azure-identity la libreria e usare il token come password. Ottenere informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
conn_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
conn = psycopg2.connect(conn_string + ' password=' + accessToken.token)
Installare le dipendenze.
pip install azure-identity
Ottenere il token di accesso usando la azure-identity libreria usando le variabili di ambiente aggiunte da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
Nel file di impostazione ottenere informazioni sul database PostgreSQL di Azure dalle variabili di ambiente aggiunte dal servizio Connessione or. Usare accessToken acquisito nel passaggio precedente per accedere al database.
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
Installare le dipendenze.
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
Nel codice ottenere il token di accesso usando azidentity, quindi usarlo come password per connettersi ad Azure PostgreSQL insieme alle informazioni di connessione fornite da Service Connessione or. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
// Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
Nel codice ottenere il token di accesso usando @azure/identity e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio service Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
// Use the token and the connection information from the environment variables added by Service Connector to establish the connection.
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: accesstoken.token,
database: process.env.AZURE_POSTGRESQL_DATABASE,
port: Number(process.env.AZURE_POSTGRESQL_PORT) ,
ssl: process.env.AZURE_POSTGRESQL_SSL
});
await client.connect();
await client.end();
})();
Per PHP, non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Nel codice ottenere il token di accesso usando l'API REST con la libreria preferita.
Per l'identità assegnata dall'utente e l'identità assegnata dal sistema, servizio app e App contenitore fornisce un endpoint REST accessibile internamente per recuperare i token per le identità gestite definendo due variabili di ambiente: IDENTITY_ENDPOINT e IDENTITY_HEADER. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
Ottenere il token di accesso effettuando una richiesta HTTP GET all'endpoint di identità e usarlo https://ossrdbms-aad.database.windows.net come resource nella query. Per l'identità assegnata dall'utente, includere anche l'ID client dalle variabili di ambiente aggiunte da Service Connessione or nella query.
Per l'entità servizio, vedere la richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare i dettagli su come acquisire il token di accesso. Effettuare la richiesta POST per l'ambito di https://ossrdbms-aad.database.windows.net/.default e con l'ID tenant, l'ID client e il segreto client dell'entità servizio dalle variabili di ambiente aggiunte da Service Connessione or.
Combinare il token di accesso e l'sting della connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or per stabilire la connessione.
Per Ruby non è disponibile un plug-in o una libreria per le connessioni senza password. È possibile ottenere un token di accesso per l'identità gestita o l'entità servizio e usarlo come password per connettersi al database. Il token di accesso può essere acquisito usando l'API REST di Azure.
Installare le dipendenze.
gem install pg
Nel codice ottenere il token di accesso usando l'API REST e le informazioni di connessione PostgreSQL dalle variabili di ambiente aggiunte dal servizio Connessione or. Combinarli per stabilire la connessione. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Il servizio app e le app del contenitore forniscono un endpoint REST accessibile internamente per recuperare i token per le identità gestite. Per altre informazioni, vedere Informazioni di riferimento sull'endpoint REST.
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client-id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
Fare riferimento alla richiesta di token di accesso da servizio a servizio di Azure AD per visualizzare altri dettagli su come acquisire il token di accesso per l'entità servizio.
Per altre lingue, usare le proprietà di connessione impostate da Service Connessione or sulle variabili di ambiente per connettere il database. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Database di Azure per PostgreSQL con Service Connessione or.
Successivamente, se sono state create tabelle e sequenze nel server flessibile PostgreSQL prima di usare Service Connessione or, è necessario connettersi come proprietario e concedere l'autorizzazione a <aad-username> creata da Service Connessione or. Il nome utente del stringa di connessione o della configurazione impostato da Service Connessione or dovrebbe essere simile aad_<connection name>a . Se si usa il portale di Azure, selezionare il pulsante di espansione accanto alla Service Type colonna e ottenere il valore. Se si usa l'interfaccia della riga di comando di Azure, archiviare configurations l'output del comando dell'interfaccia della riga di comando.
Eseguire quindi la query per concedere l'autorizzazione
az extension add --name rdbms-connect
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \"<aad-username>\";GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO \"<aad username>\";"
<owner-username> e <owner-password> è il proprietario della tabella esistente che può concedere autorizzazioni ad altri utenti. <aad-username>è l'utente creato da Service Connessione or. Sostituirli con il valore effettivo.
Convalidare il risultato con il comando :
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "SELECT distinct(table_name) FROM information_schema.table_privileges WHERE grantee='<aad-username>' AND table_schema='public';" --output table
Passaggi successivi
Seguire le esercitazioni elencate di seguito per altre informazioni su Service Connessione or.