Koneksi tanpa kata sandi menggunakan identitas terkelola untuk mengakses layanan Azure. Dengan pendekatan ini, Anda tidak perlu melacak dan mengelola rahasia secara manual untuk identitas terkelola. Tugas-tugas ini ditangani dengan aman secara internal oleh Azure.
Konektor Layanan memungkinkan identitas terkelola dalam layanan hosting aplikasi seperti Azure Spring Apps, Azure App Service, dan Azure Container Apps. Konektor Layanan juga mengonfigurasi layanan database, seperti Azure Database for PostgreSQL, Azure Database for MySQL, Azure SQL Database, dan database SQL di Microsoft Fabric, untuk menerima identitas terkelola.
Di tutorial ini, Anda menggunakan Azure CLI untuk menyelesaikan tugas berikut:
- Periksa lingkungan awal Anda dengan Azure CLI.
- Buat koneksi tanpa kata sandi dengan Konektor Layanan.
- Gunakan variabel lingkungan atau konfigurasi yang dihasilkan oleh Konektor Layanan untuk mengakses layanan database.
Prasyarat
Untuk mulai menggunakan Azure CLI:
Instal ekstensi konektor layanan tanpa perlu kata sandi
Instal ekstensi tanpa kata sandi Konektor Layanan terbaru untuk Azure CLI:
az extension add --name serviceconnector-passwordless --upgrade
Nota
Silakan periksa ekstensi "serviceconnector-passwordless" versi "2.0.2" atau lebih tinggi dengan menjalankan az version
. Anda mungkin perlu meningkatkan Azure CLI terlebih dahulu untuk meningkatkan versi ekstensi.
Membuat koneksi tanpa kata sandi
Selanjutnya, kami menggunakan Azure App Service sebagai contoh untuk membuat koneksi menggunakan identitas terkelola.
Jika Anda menggunakan:
Nota
Jika Anda menggunakan portal Microsoft Azure, buka bilah Konektor LayananAzure App Service, Azure Spring Apps, atau Azure Container Apps, dan pilih Buat untuk membuat koneksi. Portal Microsoft Azure akan secara otomatis menyusun perintah untuk Anda dan memicu eksekusi perintah di Cloud Shell.
Perintah Azure CLI berikut menggunakan --client-type
parameter, bisa berupa java, dotnet, python, dll. Jalankan az webapp connection create postgres-flexible -h
untuk mendapatkan jenis klien yang didukung, dan pilih yang cocok dengan aplikasi Anda.
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX \
--client-type $CLIENT_TYPE
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type $CLIENT_TYPE
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX\
--client-type $CLIENT_TYPE
Azure Database for MySQL - Server Fleksibel memerlukan identitas terkelola yang ditetapkan pengguna untuk mengaktifkan autentikasi Microsoft Entra. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi Microsoft Entra untuk Azure Database for MySQL - Server Fleksibel. Anda dapat menggunakan perintah berikut untuk membuat identitas terkelola yang ditetapkan pengguna:
USER_IDENTITY_NAME=<YOUR_USER_ASSIGNED_MANAGED_IDENTITY_NAME>
IDENTITY_RESOURCE_ID=$(az identity create \
--name $USER_IDENTITY_NAME \
--resource-group $RESOURCE_GROUP \
--query id \
--output tsv)
Penting
Setelah membuat identitas terkelola yang ditetapkan pengguna, minta Administrator Global atau Administrator Peran Istimewa Anda untuk memberikan izin berikut untuk identitas ini:
User.Read.All
GroupMember.Read.All
Application.Read.All
Untuk informasi selengkapnya, lihat bagian Izin dari autentikasi Direktori Aktif.
Kemudian, sambungkan aplikasi Anda ke database MySQL dengan identitas terkelola yang ditetapkan sistem menggunakan Konektor Layanan.
Perintah Azure CLI berikut menggunakan --client-type
parameter . Jalankan az webapp connection create mysql-flexible -h
untuk mendapatkan jenis klien yang didukung, dan pilih yang cocok dengan aplikasi Anda.
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--system-identity mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
Perintah Azure CLI berikut menggunakan --client-type
parameter . Jalankan az webapp connection create sql -h
untuk mendapatkan jenis klien yang didukung, dan pilih yang cocok dengan aplikasi Anda.
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX \
--client-type dotnet
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type dotnet
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX \
--client-type dotnet
Perintah Azure CLI berikut menggunakan --client-type
parameter . Jalankan az webapp connection create fabricsql -h
untuk mendapatkan jenis klien yang didukung, dan pilih yang cocok dengan aplikasi Anda.
az webapp connection create fabricsql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--fabric-workspace-uuid $FABRIC_WORKSPACE_UUID \
--fabric-sql-db-uuid $FABRIC_SQL_DB_UUID \
--user-identity client-id=XX subs-id=XX \
--client-type dotnet
az webapp connection create fabricsql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--fabric-workspace-uuid $FABRIC_WORKSPACE_UUID \
--fabric-sql-db-uuid $FABRIC_SQL_DB_UUID \
--system-identity \
--client-type dotnet
Nota
Koneksi layanan yang menggunakan prinsipal layanan tidak didukung saat menargetkan database SQL di Microsoft Fabric.
Perintah Konektor Layanan ini menyelesaikan tugas berikut di latar belakang:
- Aktifkan identitas terkelola yang ditetapkan sistem, atau tetapkan identitas pengguna untuk aplikasi
$APPSERVICE_NAME
yang dihosting oleh Azure App Service/Azure Spring Apps/Azure Container Apps.
- Aktifkan Microsoft Entra Authentication untuk server database jika tidak diaktifkan sebelumnya.
- Tetapkan admin Microsoft Entra kepada pengguna yang sedang masuk.
- Tambahkan pengguna database untuk identitas terkelola yang ditetapkan sistem, identitas terkelola yang ditetapkan pengguna, atau perwakilan layanan. Berikan semua hak istimewa database
$DATABASE_NAME
kepada pengguna ini. Nama pengguna dapat ditemukan di string koneksi dalam output perintah sebelumnya.
- Atur konfigurasi bernama
AZURE_MYSQL_CONNECTIONSTRING
, AZURE_POSTGRESQL_CONNECTIONSTRING
, AZURE_SQL_CONNECTIONSTRING
, atau FABRIC_SQL_CONNECTIONSTRING
ke sumber daya Azure berdasarkan jenis database.
- Untuk App Service, konfigurasi diatur di bilah Pengaturan Aplikasi.
- Untuk Spring Apps, konfigurasi diatur saat aplikasi diluncurkan.
- Untuk Container Apps, konfigurasi diatur ke variabel lingkungan. Anda bisa mendapatkan semua konfigurasi dan nilainya di bilah Konektor Layanan di portal Microsoft Azure.
Konektor Layanan akan menetapkan hak istimewa berikut kepada pengguna, Anda dapat mencabutnya dan menyesuaikan hak istimewa berdasarkan kebutuhan Anda.
GRANT ALL PRIVILEGES ON DATABASE "$DATABASE_NAME" TO "username";
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "username";
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO "username";
GRANT ALL PRIVILEGES ON $DATABASE_NAME.* TO 'username'@'%';
GRANT CONTROL ON DATABASE::"$DATABASE_NAME" TO "username";
ALTER ROLE db_datareader ADD MEMBER "username"
ALTER ROLE db_datawriter ADD MEMBER "username"
ALTER ROLE db_ddladmin ADD MEMBER "username"
Menyambungkan ke database dengan autentikasi Microsoft Entra
Setelah membuat koneksi, Anda dapat menggunakan string koneksi di aplikasi Anda untuk menyambungkan ke database dengan autentikasi Microsoft Entra. Misalnya, Anda dapat menggunakan solusi berikut untuk menyambungkan ke database dengan autentikasi Microsoft Entra.
Untuk .NET, tidak ada plugin atau pustaka untuk mendukung koneksi tanpa kata sandi. Anda bisa mendapatkan token akses untuk identitas terkelola atau perwakilan layanan menggunakan pustaka klien seperti Azure.Identity. Kemudian Anda dapat menggunakan token akses sebagai kata sandi untuk menyambungkan ke database. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
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();
}
Tambahkan dependensi berikut dalam file pom.xml Anda:
<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>
Dapatkan string koneksi dari variabel lingkungan dan tambahkan nama plugin untuk menyambungkan ke 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);
Untuk informasi selengkapnya, lihat sumber daya berikut ini:
Instal dependensi.
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
Dapatkan token akses menggunakan azure-identity
pustaka dan gunakan token sebagai kata sandi. Dapatkan informasi koneksi dari variabel lingkungan yang ditambahkan oleh Konektor Layanan. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
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)
Instal dependensi.
pip install azure-identity
Dapatkan token akses menggunakan azure-identity
pustaka menggunakan variabel lingkungan yang ditambahkan oleh Konektor Layanan. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
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')
Dalam berkas pengaturan, dapatkan informasi database Azure PostgreSQL dari variabel lingkungan yang ditambahkan oleh layanan Service Connector. Gunakan accessToken
yang diperoleh pada langkah sebelumnya untuk mengakses 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'},
}
}
Instal dependensi.
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"
Dalam kode, dapatkan token akses menggunakan azidentity
, lalu gunakan sebagai kata sandi untuk terhubung ke Azure PostgreSQL bersama dengan informasi koneksi yang disediakan oleh Konektor Layanan. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
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()
Instal dependensi.
npm install --save @azure/identity
npm install --save pg
Dalam kode, dapatkan token akses menggunakan @azure/identity
dan informasi koneksi PostgreSQL dari variabel lingkungan yang ditambahkan oleh layanan Konektor Layanan. Gabungkan untuk membuat koneksi. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
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();
})();
Untuk PHP, tidak ada plugin atau pustaka untuk koneksi tanpa kata sandi. Anda bisa mendapatkan token akses untuk identitas terkelola atau perwakilan layanan dan menggunakannya sebagai kata sandi untuk menyambungkan ke database. Token akses dapat diperoleh menggunakan Azure REST API.
Dalam kode, dapatkan token akses menggunakan REST API dengan pustaka favorit Anda.
Untuk identitas yang ditetapkan pengguna dan identitas yang ditetapkan sistem, App Service dan Container Apps menyediakan titik akhir REST yang dapat diakses secara internal untuk mengambil token untuk identitas terkelola dengan menentukan dua variabel lingkungan: IDENTITY_ENDPOINT
dan IDENTITY_HEADER
. Untuk informasi selengkapnya, lihat Referensi titik akhir REST.
Dapatkan token akses dengan membuat permintaan HTTP GET ke titik akhir identitas, dan gunakan https://ossrdbms-aad.database.windows.net
seperti resource
dalam kueri. Untuk identitas yang ditetapkan pengguna, sertakan ID klien dari variabel lingkungan yang ditambahkan oleh Konektor Layanan dalam kueri juga.
Untuk perwakilan layanan, lihat permintaan token akses layanan-ke-layanan Azure AD untuk melihat detail cara memperoleh token akses. Buat permintaan POST pada ruang lingkup https://ossrdbms-aad.database.windows.net/.default
serta ID penyewa, ID klien, dan rahasia klien dari perwakilan layanan berdasarkan variabel lingkungan yang ditambahkan oleh Konektor Layanan.
Gabungkan token akses dan string koneksi PostgreSQL dari variabel lingkungan yang ditambahkan oleh layanan Konektor Layanan untuk membuat koneksi.
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
Untuk Ruby, tidak ada plugin atau pustaka untuk koneksi tanpa kata sandi. Anda bisa mendapatkan token akses untuk identitas terkelola atau perwakilan layanan dan menggunakannya sebagai kata sandi untuk menyambungkan ke database. Token akses dapat diperoleh menggunakan Azure REST API.
Instal dependensi.
gem install pg
Dalam kode, dapatkan token akses menggunakan REST API dan informasi koneksi PostgreSQL dari variabel lingkungan yang ditambahkan oleh layanan Konektor Layanan. Gabungkan untuk membuat koneksi. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
App service dan container Apps menyediakan titik akhir REST yang dapat diakses secara internal untuk mengambil token untuk identitas terkelola. Untuk informasi selengkapnya, lihat Referensi titik akhir 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,
)
Lihat permintaan token akses layanan-ke-layanan dari layanan Azure AD untuk informasi lebih lanjut tentang cara mendapatkan token akses perwakilan layanan.
Selanjutnya, jika Anda telah membuat tabel dan urutan di server fleksibel PostgreSQL sebelum menggunakan Konektor Layanan, Anda perlu terhubung sebagai pemilik dan memberikan izin untuk <aad-username>
dibuat oleh Konektor Layanan. Nama pengguna dari string koneksi atau konfigurasi yang ditetapkan oleh Konektor Layanan akan terlihat seperti aad_<connection name>
. Jika Anda menggunakan portal Azure, pilih tombol perluas di Service Type
samping kolom dan dapatkan nilainya. Jika Anda menggunakan Azure CLI, periksa configurations
output perintah CLI.
Kemudian, jalankan kueri untuk memberikan izin
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>
dan <owner-password>
adalah pemilik tabel yang ada yang dapat memberikan izin kepada orang lain.
<aad-username>
adalah pengguna yang dibuat oleh Konektor Layanan. Ganti dengan nilai aktual.
Validasi hasil dengan perintah :
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
Untuk .NET, tidak ada plugin atau pustaka untuk mendukung koneksi tanpa kata sandi. Anda bisa mendapatkan token akses untuk identitas terkelola atau perwakilan layanan menggunakan pustaka klien seperti Azure.Identity. Kemudian Anda dapat menggunakan token akses sebagai kata sandi untuk menyambungkan ke database. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
using Azure.Core;
using Azure.Identity;
using MySqlConnector;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// var credential = new DefaultAzureCredential();
// For user-assigned managed identity.
// var credential = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// });
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_MYSQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTSECRET");
// var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.windows.net/.default" });
AccessToken accessToken = await credential.GetTokenAsync(tokenRequestContext);
// Open a connection to the MySQL server using the access token.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING")};Password={accessToken.Token}";
using var connection = new MySqlConnection(connectionString);
Console.WriteLine("Opening connection using access token...");
await connection.OpenAsync();
// do something
Tambahkan dependensi berikut dalam file pom.xml Anda:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
Dapatkan string koneksi dari variabel lingkungan, dan tambahkan nama plugin untuk menyambungkan ke database:
String url = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.mysql.AzureMysqlAuthenticationPlugin";
Properties properties = new Properties();
properties.put("defaultAuthenticationPlugin", pluginName);
properties.put("authenticationPlugins", pluginName);
// Uncomment the following lines corresponding to the authentication type you want to use.
// for user-assigned managed identity
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// properties.put("azure.clientId", clientId);
// For service principal
// String tenantId = System.getenv('AZURE_MYSQL_TENANTID')
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// String clientSecret = System.getenv('AZURE_MYSQL_CLIENTSECRET')
// properties.put("azure.clientId", clientId);
// properties.put("azure.clientSecret", clientSecret);
// properties.put("azure.tenantId", tenantId);
Connection connection = DriverManager.getConnection(url, properties);
Untuk informasi selengkapnya, lihat Menggunakan Java dan JDBC dengan Azure Database for MySQL - Server Fleksibel.
Pasang dependensi
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
Autentikasi dengan mendapatkan token akses melalui pustaka azure-identity
dan memperoleh informasi koneksi dari variabel lingkungan yang ditambahkan oleh Konektor Layanan. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import mysql.connector
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# cred = ManagedIdentityCredential()
# For user-assigned managed identity.
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# open connect to Azure MySQL with the access token.
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token
cnx = mysql.connector.connect(user=user,
password=password,
host=host,
database=database)
cnx.close()
Instal dependensi.
pip install azure-identity
Dapatkan token akses melalui pustaka azure-identity
dengan variabel lingkungan yang telah ditambahkan oleh Service Connector. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# system-assigned managed identity
# cred = ManagedIdentityCredential()
# user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
Dalam pengaturan file, dapatkan informasi database Azure MySQL dari variabel lingkungan yang ditambahkan oleh layanan Service Connector. Gunakan accessToken
yang diperoleh pada langkah sebelumnya untuk mengakses database.
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
Instal dependensi.
go get "github.com/go-sql-driver/mysql"
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
Dalam kode, dapatkan token akses melalui azidentity
, lalu sambungkan ke Azure MySQL dengan token. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/go-sql-driver/mysql"
)
func main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// for user-assigned managed identity
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// for service principal
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// tenantid := os.Getenv("AZURE_MYSQL_TENANTID")
// clientsecret := os.Getenv("AZURE_MYSQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING") + ";Password=" + token.Token
db, err := sql.Open("mysql", connectionString)
}
Pasang dependensi
npm install --save @azure/identity
npm install --save mysql2
Dapatkan token akses menggunakan @azure/identity
dan informasi database Azure MySQL dari variabel lingkungan yang ditambahkan oleh Layanan Service Connector. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// const credential = new DefaultAzureCredential();
// for user-assigned managed identity
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// for service principal
// const tenantId = process.env.AZURE_MYSQL_TENANTID;
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const clientSecret = process.env.AZURE_MYSQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: accessToken.token,
database: process.env.AZURE_MYSQL_DATABASE,
port: process.env.AZURE_MYSQL_PORT,
ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database');
});
Untuk sampel kode lainnya, lihat Menyambungkan ke database Azure dari App Service tanpa rahasia menggunakan identitas terkelola.
Instal dependensi.
dotnet add package Microsoft.Data.SqlClient
Dapatkan string koneksi Azure SQL Database dari variabel lingkungan yang ditambahkan oleh Konektor Layanan.
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
Untuk informasi selengkapnya, lihat Menggunakan autentikasi Identitas Terkelola Active Directory.
Tambahkan dependensi berikut dalam file pom.xml Anda:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</version>
</dependency>
Dapatkan string koneksi Azure SQL Database dari variabel lingkungan yang ditambahkan oleh Konektor Layanan.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class Main {
public static void main(String[] args) {
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};msiClientId={UserAssignedMiClientId};authentication=ActiveDirectoryMSI;"
// For service principal: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};user={ServicePrincipalClientId};password={spSecret};authentication=ActiveDirectoryServicePrincipal;"
String connectionString = System.getenv("AZURE_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Untuk informasi selengkapnya, lihat Menyambungkan ke database Azure dari App Service tanpa rahasia menggunakan identitas terkelola.
Untuk aplikasi Spring, jika Anda membuat koneksi dengan opsi --client-type springboot
, Service Connector mengatur properti spring.datasource.url
dengan format nilai jdbc:sqlserver://<sql-server>.database.windows.net:1433;databaseName=<sql-db>;authentication=ActiveDirectoryMSI;
ke Azure Spring Apps.
Perbarui aplikasi Anda dengan mengikuti tutorial Memigrasikan aplikasi Java untuk menggunakan koneksi tanpa kata sandi dengan Azure SQL Database. Ingatlah untuk menghapus properti konfigurasi spring.datasource.password
jika sudah diatur sebelumnya dan tambahkan dependensi yang sesuai.
Instal dependensi.
python -m pip install pyodbc
Dapatkan konfigurasi koneksi Azure SQL Database dari variabel lingkungan yang ditambahkan oleh Konektor Layanan. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan. Jika Anda menggunakan Azure Container Apps sebagai layanan komputasi atau string koneksi dalam cuplikan kode tidak berfungsi, lihat Memigrasikan aplikasi Python untuk menggunakan koneksi tanpa kata sandi dengan Azure SQL Database untuk menyambungkan ke Azure SQL Database menggunakan token akses.
import os
import pyodbc
server = os.getenv('AZURE_SQL_SERVER')
port = os.getenv('AZURE_SQL_PORT')
database = os.getenv('AZURE_SQL_DATABASE')
authentication = os.getenv('AZURE_SQL_AUTHENTICATION')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For user-assigned managed identity.
# clientID = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={clientID};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For service principal.
# user = os.getenv('AZURE_SQL_USER')
# password = os.getenv('AZURE_SQL_PASSWORD')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={user};PWD={password};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
conn = pyodbc.connect(connString)
- Instal dependensi.
npm install mssql
- Dapatkan konfigurasi koneksi Azure SQL Database dari variabel lingkungan yang ditambahkan oleh Konektor Layanan. Saat menggunakan kode di bawah ini, hapus tanda komentar pada bagian cuplikan kode untuk jenis autentikasi yang ingin Anda gunakan.
import sql from 'mssql';
const server = process.env.AZURE_SQL_SERVER;
const database = process.env.AZURE_SQL_DATABASE;
const port = parseInt(process.env.AZURE_SQL_PORT);
const authenticationType = process.env.AZURE_SQL_AUTHENTICATIONTYPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true
// }
// };
// For user-assigned managed identity.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId
// }
// };
// For service principal.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const clientSecret = process.env.AZURE_SQL_CLIENTSECRET;
// const tenantId = process.env.AZURE_SQL_TENANTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId,
// clientSecret: clientSecret,
// tenantId: tenantId
// }
// };
this.poolconnection = await sql.connect(config);
Untuk informasi selengkapnya, lihat Beranda untuk pemrograman klien ke Microsoft SQL Server.
Instal dependensi.
dotnet add package Microsoft.Data.SqlClient
Ambil database SQL dalam string koneksi Microsoft Fabric dari variabel lingkungan yang ditambahkan oleh Konektor Layanan.
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("FABRIC_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
Untuk informasi selengkapnya, lihat Menggunakan autentikasi identitas terkelola Direktori Aktif.
Tambahkan dependensi berikut dalam file pom.xml Anda:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</version>
</dependency>
Ambil database SQL dalam string koneksi Microsoft Fabric dari variabel lingkungan yang ditambahkan oleh Konektor Layanan.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class Main {
public static void main(String[] args) {
// FABRIC_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;msiClientId=<msiClientId>;authentication=ActiveDirectoryMSI;"
String connectionString = System.getenv("FABRIC_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Untuk informasi selengkapnya, lihat Menyambungkan ke database Azure dari App Service tanpa rahasia menggunakan identitas terkelola.
Untuk aplikasi Spring, jika Anda membuat koneksi dengan opsi --client-type springboot
, Konektor Layanan menetapkan variabel lingkungan FABRIC_SQL_CONNECTIONSTRING
dengan nilai dalam format jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;
untuk Azure Spring Apps.
Untuk identitas terkelola yang ditetapkan pengguna, msiClientId=<msiClientId>;
ditambahkan.
Perbarui aplikasi Anda dengan mengikuti tutorial Memigrasikan aplikasi Java untuk menggunakan koneksi tanpa kata sandi dengan Azure SQL Database. Jangan lupa untuk menghapus spring.datasource.password
properti konfigurasi jika sebelumnya diatur dan tambahkan dependensi yang sesuai.
spring:
datasource:
url: ${FABRIC_SQL_CONNECTIONSTRING}
Instal dependensi.
python -m pip install pyodbc
Ambil database SQL dalam string koneksi Microsoft Fabric dari variabel lingkungan yang ditambahkan oleh Konektor Layanan. Jika Anda menggunakan Azure Container Apps sebagai layanan komputasi atau string koneksi dalam cuplikan kode tidak berfungsi, lihat Memigrasikan aplikasi Python untuk menggunakan koneksi tanpa kata sandi dengan Azure SQL Database untuk menyambungkan ke database SQL di Microsoft Fabric menggunakan kredensial tanpa kata sandi.
Authentication=ActiveDirectoryMSI;
diperlukan dalam string koneksi saat menyambungkan menggunakan identitas terkelola.
UID=<msiClientId>
juga diperlukan dalam string koneksi saat menyambungkan menggunakan identitas terkelola yang ditetapkan pengguna.
import os
import pyodbc, struct
from azure.identity import DefaultAzureCredential
connStr = os.getenv('FABRIC_SQL_CONNECTIONSTRING')
# System-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;Authentication=ActiveDirectoryMSI;`
# User-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;UID=<msiClientId>;Authentication=ActiveDirectoryMSI;`
conn = pyodbc.connect(connString)
- Instal dependensi.
go mod init <YourProjectName>
go mod tidy
- Ambil database SQL dalam string koneksi Microsoft Fabric dari variabel lingkungan yang ditambahkan oleh Konektor Layanan.
package main
import (
"github.com/microsoft/go-mssqldb/azuread"
"database/sql"
"context"
"log"
"fmt"
"os"
)
var db *sql.DB
var connectionString = os.Getenv("FABRIC_SQL_CONNECTIONSTRING")
func main() {
var err error
// Create connection pool
db, err = sql.Open(azuread.DriverName, connectionString)
if err != nil {
log.Fatal("Error creating connection pool: ", err.Error())
}
ctx := context.Background()
err = db.PingContext(ctx)
if err != nil {
log.Fatal(err.Error())
}
fmt.Printf("Connected!\n")
}
Untuk informasi selengkapnya, lihat Menggunakan Golang untuk mengkueri database di Azure SQL Database.
Untuk informasi selengkapnya, lihat Menyambungkan ke database SQL Anda di Microsoft Fabric.
Menyebarkan aplikasi ke layanan hosting Azure
Sebarkan aplikasi Anda ke layanan hosting Azure. Secara opsional lihat panduan di bawah ini untuk informasi selengkapnya tentang menyebarkan sumber daya ini.
Periksa log atau panggil aplikasi untuk melihat apakah aplikasi berhasil tersambung ke database Azure.
Penyelesaian Masalah
Hak akses
Jika Anda mengalami kesalahan terkait izin, konfirmasikan pengguna masuk Azure CLI dengan perintah az account show
. Pastikan Anda masuk dengan akun yang benar. Selanjutnya, konfirmasikan bahwa Anda memiliki izin berikut yang mungkin diperlukan untuk membuat koneksi tanpa kata sandi dengan Konektor Layanan.
Persetujuan |
Operasi |
Microsoft.DBforPostgreSQL/flexibleServers/read |
Diperlukan untuk mendapatkan informasi server database |
Microsoft.DBforPostgreSQL/flexibleServers/write |
Diperlukan untuk mengaktifkan autentikasi Microsoft Entra untuk server database |
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/write |
Diperlukan untuk membuat aturan firewall jika alamat IP lokal diblokir |
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/delete |
Diperlukan untuk mengembalikan aturan firewall yang dibuat oleh Konektor Layanan untuk menghindari masalah keamanan |
Microsoft.DBforPostgreSQL/flexibleServers/administrators/read |
Diperlukan untuk memeriksa apakah pengguna login Azure CLI adalah administrator Microsoft Entra server database |
Microsoft.DBforPostgreSQL/flexibleServers/administrators/write |
Diperlukan untuk menambahkan pengguna yang masuk Azure CLI sebagai administrator Microsoft Entra di server database |
Persetujuan |
Operasi |
Microsoft.DBforMySQL/flexibleServers/read |
Diperlukan untuk mendapatkan informasi server database |
Microsoft.DBforMySQL/flexibleServers/write |
Diperlukan untuk menambahkan identitas terkelola yang ditetapkan Pengguna yang disediakan ke server database |
Microsoft.DBforMySQL/flexibleServers/firewallRules/write |
Diperlukan untuk membuat aturan firewall jika alamat IP lokal diblokir |
Microsoft.DBforMySQL/flexibleServers/firewallRules/delete |
Diperlukan untuk mengembalikan aturan firewall yang dibuat oleh Konektor Layanan untuk menghindari masalah keamanan |
Microsoft.DBforMySQL/flexibleServers/administrators/read |
Diperlukan untuk memeriksa apakah pengguna login Azure CLI adalah administrator Microsoft Entra server database |
Microsoft.DBforMySQL/flexibleServers/administrators/write |
Diperlukan untuk menambahkan pengguna yang masuk Azure CLI sebagai administrator Microsoft Entra di server database |
Persetujuan |
Operasi |
Microsoft.Sql/servers/read |
Diperlukan untuk mendapatkan informasi server database |
Microsoft.Sql/servers/firewallRules/write |
Diperlukan untuk membuat aturan firewall jika alamat IP lokal diblokir |
Microsoft.Sql/servers/firewallRules/delete |
Diperlukan untuk mengembalikan aturan firewall yang dibuat oleh Konektor Layanan untuk menghindari masalah keamanan |
Microsoft.Sql/servers/administrators/read |
Diperlukan untuk memeriksa apakah pengguna login Azure CLI adalah administrator Microsoft Entra server database |
Microsoft.Sql/servers/administrators/write |
Diperlukan untuk menambahkan pengguna yang masuk Azure CLI sebagai administrator Microsoft Entra di server database |
Dalam beberapa kasus, izin tidak diperlukan. Misalnya, jika pengguna yang diautentikasi Azure CLI sudah menjadi Administrator Direktori Aktif di server SQL, Anda tidak perlu memiliki Microsoft.Sql/servers/administrators/write
izin.
Microsoft Entra ID
Jika Anda mengalami kesalahan ERROR: AADSTS530003: Your device is required to be managed to access this resource.
, minta bantuan departemen IT Anda untuk menghubungkan perangkat ini ke Microsoft Entra ID. Untuk informasi selengkapnya, lihat Perangkat gabungan Microsoft Entra.
Konektor Layanan perlu mengakses ID Microsoft Entra untuk mendapatkan informasi tentang akun Anda dan identitas terkelola layanan hosting. Anda dapat menggunakan perintah berikut untuk memeriksa apakah perangkat Anda dapat mengakses ID Microsoft Entra:
az ad signed-in-user show
Jika Anda tidak masuk secara interaktif, Anda mungkin juga mendapatkan kesalahan dan Interactive authentication is needed
. Untuk mengatasi kesalahan, masuk dengan perintah az login
.
Konektivitas jaringan
Jika server database Anda berada di Virtual Network, pastikan lingkungan Anda yang menjalankan perintah Azure CLI dapat mengakses server di Virtual Network.
Jika server database Anda berada di Virtual Network, pastikan lingkungan Anda yang menjalankan perintah Azure CLI dapat mengakses server di Virtual Network.
Jika server database Anda melarang akses publik, pastikan lingkungan Anda yang menjalankan perintah Azure CLI dapat mengakses server melalui titik akhir privat.
Langkah selanjutnya
Untuk informasi selengkapnya tentang Konektor Layanan dan koneksi tanpa kata sandi, lihat sumber daya berikut: