Integrare Azure Cosmos DB per Cassandra 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 connettere Azure Cosmos DB per Apache Cassandra ad altri servizi cloud usando Service Connessione or. È comunque possibile connettersi ad Azure Cosmos DB per Cassandra 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 ad Azure Cosmos DB per Apache Cassandra:
Servizio app di Azure
Funzioni di Azure
App contenitore di Azure
Azure Spring Apps
Tipi di autenticazione e tipi di client supportati
La tabella seguente illustra le combinazioni di tipi client e metodi di autenticazione supportati per la connessione del servizio di calcolo ad Azure Cosmos DB per Apache Cassandra 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
Sì
Sì
Sì
Sì
Java
Sì
Sì
Sì
Sì
Java - Spring Boot
No
No
Sì
No
Node.js
Sì
Sì
Sì
Sì
Python
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, ad eccezione del tipo di client Java - Spring Boot, che supporta solo il metodo Secret/stringa di connessione. Tutti gli altri tipi di client possono usare uno dei metodi di autenticazione per connettersi ad Azure Cosmos DB per Apache Cassandra tramite Service Connessione or.
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 ad Azure Cosmos DB per Apache Cassandra. Per altre informazioni sulle convenzioni di denominazione, vedere l'articolo Servizi Connessione or internals .
Ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client Azure.Identity. Usare il token di accesso e AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Cassandra;
using Azure.Identity;
public class Program
{
public static async Task Main()
{
var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var tokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var tokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
// var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await tokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]{ scope }));
// Get the password.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.POSTAsync(listKeyUrl);
var responseBody = await response.Content.ReadAsStringAsync();
var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);
var password = keys["primaryMasterKey"];
// Connect to Azure Cosmos DB for Cassandra
var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
Cluster cluster = Cluster
.Builder()
.WithCredentials(userName, password)
.WithPort(cassandraPort)
.AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
ISession session = await cluster.ConnectAsync();
}
public static bool ValidateServerCertificate
(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
}
Aggiungere le dipendenze seguenti nel file pom.xml :
Ottenere un token di accesso per l'identità gestita o l'entità servizio usando azure-identity. Usare il token di accesso e AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 com.datastax.oss.driver.api.core.CqlSession;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credentital.*;
import java.net.http.*;
import java.net.URI;
int cassandraPort = Integer.parseInt(System.getenv("AZURE_COSMOS_PORT"));
String cassandraUsername = System.getenv("AZURE_COSMOS_USERNAME");
String cassandraHost = System.getenv("AZURE_COSMOS_CONTACTPOINT");
String cassandraKeyspace = System.getenv("AZURE_COSMOS_KEYSPACE");
String listKeyUrl = System.getenv("AZURE_COSMOS_LISTKEYURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines according to the authentication type.
// For system managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
// For user assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
// .managedIdentityClientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .build();
// For service principal.
// ClientSecretCredential defaultCredential = new ClientSecretCredentialBuilder()
// .clientId(System.getenv("<AZURE_COSMOS_CLIENTID>"))
// .clientSecret(System.getenv("<AZURE_COSMOS_CLIENTSECRET>"))
// .tenantId(System.getenv("<AZURE_COSMOS_TENANTID>"))
// .build();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the password.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listKeyUrl))
.header("Authorization", "Bearer " + token)
.POST()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONParser parser = new JSONParser();
JSONObject responseBody = parser.parse(response.body());
String cassandraPassword = responseBody.get("primaryMasterKey");
// Connect to Azure Cosmos DB for Cassandra
final SSLContext sc = SSLContext.getInstance("TLSv1.2");
CqlSession session = CqlSession.builder().withSslContext(sc)
.addContactPoint(new InetSocketAddress(cassandraHost, cassandraPort)).withLocalDatacenter('datacenter1')
.withAuthCredentials(cassandraUsername, cassandraPassword).build();
Il tipo di autenticazione non è supportato per Spring Boot.
Usare azure-identity per eseguire l'autenticazione con l'identità gestita o l'entità servizio e inviare una richiesta a AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 cassandra.cluster import Cluster
from ssl import PROTOCOL_TLSv1_2, SSLContext, CERT_NONE
from cassandra.auth import PlainTextAuthProvider
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
username = os.getenv('AZURE_COSMOS_USERNAME')
contactPoint = os.getenv('AZURE_COSMOS_CONTACTPOINT')
port = os.getenv('AZURE_COSMOS_PORT')
keyspace = os.getenv('AZURE_COSMOS_KEYSPACE')
listKeyUrl = os.getenv('AZURE_COSMOS_LISTKEYURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity
# cred = ManagedIdentityCredential()
# For user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_COSMOS_TENANTID')
# client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# client_secret = os.getenv('AZURE_COSMOS_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Get the password
session = requests.Session()
token = cred.get_token(scope)
response = session.post(listKeyUrl, headers={"Authorization": "Bearer {}".format(token.token)})
keys_dict = response.json()
password = keys_dict['primaryMasterKey']
# Connect to Azure Cosmos DB for Cassandra.
ssl_context = SSLContext(PROTOCOL_TLSv1_2)
ssl_context.verify_mode = CERT_NONE
auth_provider = PlainTextAuthProvider(username, password)
cluster = Cluster([contanctPoint], port = port, auth_provider=auth_provider,ssl_context=ssl_context)
session = cluster.connect()
Installare le dipendenze.
go get github.com/gocql/gocql
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 un token di accesso tramite azidentitye quindi usarlo per acquisire la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Nel codice ottenere il token di accesso tramite @azure/identity, quindi usarlo per acquisire la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 cassandra = require("cassandra-driver");
const axios = require('axios');
let username = process.env.AZURE_COSMOS_USERNAME;
let contactPoint = process.env.AZURE_COSMOS_CONTACTPOINT;
let port = process.env.AZURE_COSMOS_PORT;
let keyspace = process.env.AZURE_COSMOS_KEYSPACE;
let listKeyUrl = process.env.AZURE_COSMOS_LISTKEYURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// 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_COSMOS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_COSMOS_TENANTID;
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const clientSecret = process.env.AZURE_COSMOS_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken(scope);
// Get the password.
const config = {
method: 'post',
url: listKeyUrl,
headers: {
'Authorization': `Bearer ${accessToken.token}`
}
};
const response = await axios(config);
const keysDict = response.data;
const password = keysDict['primaryMasterKey'];
let authProvider = new cassandra.auth.PlainTextAuthProvider(
username,
password
);
let client = new cassandra.Client({
contactPoints: [`${contactPoint}:${port}`],
authProvider: authProvider,
localDataCenter: 'datacenter1',
sslOptions: {
secureProtocol: "TLSv1_2_method"
},
});
client.connect();
Per altri linguaggi, è possibile usare il punto di contatto Cassandra e altre proprietà impostate da Service Connessione or sulle variabili di ambiente per connettersi alla risorsa Azure Cosmos DB per Cassandra. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Azure Cosmos DB per Cassandra con Service Connessione or.
Ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client Azure.Identity. Usare il token di accesso e AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Cassandra;
using Azure.Identity;
public class Program
{
public static async Task Main()
{
var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var tokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var tokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
// var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await tokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]{ scope }));
// Get the password.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.POSTAsync(listKeyUrl);
var responseBody = await response.Content.ReadAsStringAsync();
var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);
var password = keys["primaryMasterKey"];
// Connect to Azure Cosmos DB for Cassandra
var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
Cluster cluster = Cluster
.Builder()
.WithCredentials(userName, password)
.WithPort(cassandraPort)
.AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
ISession session = await cluster.ConnectAsync();
}
public static bool ValidateServerCertificate
(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
}
Aggiungere le dipendenze seguenti nel file pom.xml :
Ottenere un token di accesso per l'identità gestita o l'entità servizio usando azure-identity. Usare il token di accesso e AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 com.datastax.oss.driver.api.core.CqlSession;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credentital.*;
import java.net.http.*;
import java.net.URI;
int cassandraPort = Integer.parseInt(System.getenv("AZURE_COSMOS_PORT"));
String cassandraUsername = System.getenv("AZURE_COSMOS_USERNAME");
String cassandraHost = System.getenv("AZURE_COSMOS_CONTACTPOINT");
String cassandraKeyspace = System.getenv("AZURE_COSMOS_KEYSPACE");
String listKeyUrl = System.getenv("AZURE_COSMOS_LISTKEYURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines according to the authentication type.
// For system managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
// For user assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
// .managedIdentityClientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .build();
// For service principal.
// ClientSecretCredential defaultCredential = new ClientSecretCredentialBuilder()
// .clientId(System.getenv("<AZURE_COSMOS_CLIENTID>"))
// .clientSecret(System.getenv("<AZURE_COSMOS_CLIENTSECRET>"))
// .tenantId(System.getenv("<AZURE_COSMOS_TENANTID>"))
// .build();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the password.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listKeyUrl))
.header("Authorization", "Bearer " + token)
.POST()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONParser parser = new JSONParser();
JSONObject responseBody = parser.parse(response.body());
String cassandraPassword = responseBody.get("primaryMasterKey");
// Connect to Azure Cosmos DB for Cassandra
final SSLContext sc = SSLContext.getInstance("TLSv1.2");
CqlSession session = CqlSession.builder().withSslContext(sc)
.addContactPoint(new InetSocketAddress(cassandraHost, cassandraPort)).withLocalDatacenter('datacenter1')
.withAuthCredentials(cassandraUsername, cassandraPassword).build();
Il tipo di autenticazione non è supportato per Spring Boot.
Usare azure-identity per eseguire l'autenticazione con l'identità gestita o l'entità servizio e inviare una richiesta a AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 cassandra.cluster import Cluster
from ssl import PROTOCOL_TLSv1_2, SSLContext, CERT_NONE
from cassandra.auth import PlainTextAuthProvider
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
username = os.getenv('AZURE_COSMOS_USERNAME')
contactPoint = os.getenv('AZURE_COSMOS_CONTACTPOINT')
port = os.getenv('AZURE_COSMOS_PORT')
keyspace = os.getenv('AZURE_COSMOS_KEYSPACE')
listKeyUrl = os.getenv('AZURE_COSMOS_LISTKEYURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity
# cred = ManagedIdentityCredential()
# For user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_COSMOS_TENANTID')
# client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# client_secret = os.getenv('AZURE_COSMOS_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Get the password
session = requests.Session()
token = cred.get_token(scope)
response = session.post(listKeyUrl, headers={"Authorization": "Bearer {}".format(token.token)})
keys_dict = response.json()
password = keys_dict['primaryMasterKey']
# Connect to Azure Cosmos DB for Cassandra.
ssl_context = SSLContext(PROTOCOL_TLSv1_2)
ssl_context.verify_mode = CERT_NONE
auth_provider = PlainTextAuthProvider(username, password)
cluster = Cluster([contanctPoint], port = port, auth_provider=auth_provider,ssl_context=ssl_context)
session = cluster.connect()
Installare le dipendenze.
go get github.com/gocql/gocql
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 un token di accesso tramite azidentitye quindi usarlo per acquisire la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Nel codice ottenere il token di accesso tramite @azure/identity, quindi usarlo per acquisire la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 cassandra = require("cassandra-driver");
const axios = require('axios');
let username = process.env.AZURE_COSMOS_USERNAME;
let contactPoint = process.env.AZURE_COSMOS_CONTACTPOINT;
let port = process.env.AZURE_COSMOS_PORT;
let keyspace = process.env.AZURE_COSMOS_KEYSPACE;
let listKeyUrl = process.env.AZURE_COSMOS_LISTKEYURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// 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_COSMOS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_COSMOS_TENANTID;
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const clientSecret = process.env.AZURE_COSMOS_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken(scope);
// Get the password.
const config = {
method: 'post',
url: listKeyUrl,
headers: {
'Authorization': `Bearer ${accessToken.token}`
}
};
const response = await axios(config);
const keysDict = response.data;
const password = keysDict['primaryMasterKey'];
let authProvider = new cassandra.auth.PlainTextAuthProvider(
username,
password
);
let client = new cassandra.Client({
contactPoints: [`${contactPoint}:${port}`],
authProvider: authProvider,
localDataCenter: 'datacenter1',
sslOptions: {
secureProtocol: "TLSv1_2_method"
},
});
client.connect();
Per altri linguaggi, è possibile usare il punto di contatto Cassandra e altre proprietà impostate da Service Connessione or sulle variabili di ambiente per connettersi alla risorsa Azure Cosmos DB per Cassandra. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Azure Cosmos DB per Cassandra con Service Connessione or.
Stringa di connessione
Tipo di client SpringBoot
Nome variabile di ambiente predefinito
Descrizione
Valore di esempio
spring.data.cassandra.contact-points
Punto di contatto di Azure Cosmos DB per Apache Cassandra
Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra.
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Cassandra;
public class Program
{
public static async Task Main()
{
var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var password = Environment.GetEnvironmentVariable("AZURE_COSMOS_PASSWORD");
var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
Cluster cluster = Cluster
.Builder()
.WithCredentials(userName, password)
.WithPort(cassandraPort)
.AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
ISession session = await cluster.ConnectAsync();
}
public static bool ValidateServerCertificate
(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
}
Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra.
const cassandra = require("cassandra-driver");
let username = process.env.AZURE_COSMOS_USERNAME;
let password = process.env.AZURE_COSMOS_PASSWORD;
let contactPoint = process.env.AZURE_COSMOS_CONTACTPOINT;
let port = process.env.AZURE_COSMOS_PORT;
let keyspace = process.env.AZURE_COSMOS_KEYSPACE;
let authProvider = new cassandra.auth.PlainTextAuthProvider(
username,
password
);
let client = new cassandra.Client({
contactPoints: [`${contactPoint}:${port}`],
authProvider: authProvider,
localDataCenter: 'datacenter1',
sslOptions: {
secureProtocol: "TLSv1_2_method"
},
});
client.connect();
Per altri linguaggi, è possibile usare il punto di contatto Cassandra e altre proprietà impostate da Service Connessione or sulle variabili di ambiente per connettersi alla risorsa Azure Cosmos DB per Cassandra. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Azure Cosmos DB per Cassandra con Service Connessione or.
Ottenere un token di accesso per l'identità gestita o l'entità servizio usando la libreria client Azure.Identity. Usare il token di accesso e AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Cassandra;
using Azure.Identity;
public class Program
{
public static async Task Main()
{
var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var tokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var tokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
// var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await tokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]{ scope }));
// Get the password.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.POSTAsync(listKeyUrl);
var responseBody = await response.Content.ReadAsStringAsync();
var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);
var password = keys["primaryMasterKey"];
// Connect to Azure Cosmos DB for Cassandra
var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
Cluster cluster = Cluster
.Builder()
.WithCredentials(userName, password)
.WithPort(cassandraPort)
.AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
ISession session = await cluster.ConnectAsync();
}
public static bool ValidateServerCertificate
(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
}
Aggiungere le dipendenze seguenti nel file pom.xml :
Ottenere un token di accesso per l'identità gestita o l'entità servizio usando azure-identity. Usare il token di accesso e AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 com.datastax.oss.driver.api.core.CqlSession;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credentital.*;
import java.net.http.*;
import java.net.URI;
int cassandraPort = Integer.parseInt(System.getenv("AZURE_COSMOS_PORT"));
String cassandraUsername = System.getenv("AZURE_COSMOS_USERNAME");
String cassandraHost = System.getenv("AZURE_COSMOS_CONTACTPOINT");
String cassandraKeyspace = System.getenv("AZURE_COSMOS_KEYSPACE");
String listKeyUrl = System.getenv("AZURE_COSMOS_LISTKEYURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines according to the authentication type.
// For system managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
// For user assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
// .managedIdentityClientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .build();
// For service principal.
// ClientSecretCredential defaultCredential = new ClientSecretCredentialBuilder()
// .clientId(System.getenv("<AZURE_COSMOS_CLIENTID>"))
// .clientSecret(System.getenv("<AZURE_COSMOS_CLIENTSECRET>"))
// .tenantId(System.getenv("<AZURE_COSMOS_TENANTID>"))
// .build();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the password.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listKeyUrl))
.header("Authorization", "Bearer " + token)
.POST()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONParser parser = new JSONParser();
JSONObject responseBody = parser.parse(response.body());
String cassandraPassword = responseBody.get("primaryMasterKey");
// Connect to Azure Cosmos DB for Cassandra
final SSLContext sc = SSLContext.getInstance("TLSv1.2");
CqlSession session = CqlSession.builder().withSslContext(sc)
.addContactPoint(new InetSocketAddress(cassandraHost, cassandraPort)).withLocalDatacenter('datacenter1')
.withAuthCredentials(cassandraUsername, cassandraPassword).build();
Il tipo di autenticazione non è supportato per Spring Boot.
Usare azure-identity per eseguire l'autenticazione con l'identità gestita o l'entità servizio e inviare una richiesta a AZURE_COSMOS_LISTKEYURL per ottenere la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 cassandra.cluster import Cluster
from ssl import PROTOCOL_TLSv1_2, SSLContext, CERT_NONE
from cassandra.auth import PlainTextAuthProvider
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
username = os.getenv('AZURE_COSMOS_USERNAME')
contactPoint = os.getenv('AZURE_COSMOS_CONTACTPOINT')
port = os.getenv('AZURE_COSMOS_PORT')
keyspace = os.getenv('AZURE_COSMOS_KEYSPACE')
listKeyUrl = os.getenv('AZURE_COSMOS_LISTKEYURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity
# cred = ManagedIdentityCredential()
# For user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_COSMOS_TENANTID')
# client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# client_secret = os.getenv('AZURE_COSMOS_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Get the password
session = requests.Session()
token = cred.get_token(scope)
response = session.post(listKeyUrl, headers={"Authorization": "Bearer {}".format(token.token)})
keys_dict = response.json()
password = keys_dict['primaryMasterKey']
# Connect to Azure Cosmos DB for Cassandra.
ssl_context = SSLContext(PROTOCOL_TLSv1_2)
ssl_context.verify_mode = CERT_NONE
auth_provider = PlainTextAuthProvider(username, password)
cluster = Cluster([contanctPoint], port = port, auth_provider=auth_provider,ssl_context=ssl_context)
session = cluster.connect()
Installare le dipendenze.
go get github.com/gocql/gocql
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 un token di accesso tramite azidentitye quindi usarlo per acquisire la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. Quando si usa il codice seguente, rimuovere il commento dalla parte del frammento di codice per il tipo di autenticazione che si vuole usare.
Nel codice ottenere il token di accesso tramite @azure/identity, quindi usarlo per acquisire la password. Ottenere le informazioni di connessione dalle variabili di ambiente aggiunte da Service Connessione or e connettersi ad Azure Cosmos DB per Cassandra. 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 cassandra = require("cassandra-driver");
const axios = require('axios');
let username = process.env.AZURE_COSMOS_USERNAME;
let contactPoint = process.env.AZURE_COSMOS_CONTACTPOINT;
let port = process.env.AZURE_COSMOS_PORT;
let keyspace = process.env.AZURE_COSMOS_KEYSPACE;
let listKeyUrl = process.env.AZURE_COSMOS_LISTKEYURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// 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_COSMOS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_COSMOS_TENANTID;
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const clientSecret = process.env.AZURE_COSMOS_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken(scope);
// Get the password.
const config = {
method: 'post',
url: listKeyUrl,
headers: {
'Authorization': `Bearer ${accessToken.token}`
}
};
const response = await axios(config);
const keysDict = response.data;
const password = keysDict['primaryMasterKey'];
let authProvider = new cassandra.auth.PlainTextAuthProvider(
username,
password
);
let client = new cassandra.Client({
contactPoints: [`${contactPoint}:${port}`],
authProvider: authProvider,
localDataCenter: 'datacenter1',
sslOptions: {
secureProtocol: "TLSv1_2_method"
},
});
client.connect();
Per altri linguaggi, è possibile usare il punto di contatto Cassandra e altre proprietà impostate da Service Connessione or sulle variabili di ambiente per connettersi alla risorsa Azure Cosmos DB per Cassandra. Per informazioni dettagliate sulle variabili di ambiente, vedere Integrare Azure Cosmos DB per Cassandra con Service Connessione or.
Passaggi successivi
Seguire le esercitazioni elencate di seguito per altre informazioni su Service Connessione or.