Integrowanie usługi Azure Cosmos DB dla języka Gremlin z łącznikiem usługi
Artykuł
Na tej stronie przedstawiono obsługiwane metody uwierzytelniania i klientów oraz pokazano przykładowy kod, za pomocą którego można połączyć usługę Azure Cosmos DB dla języka Apache Gremlin z innymi usługami w chmurze przy użyciu łącznika usług. Nadal możesz nawiązać połączenie z usługą Azure Cosmos DB dla języka Gremlin w innych językach programowania bez używania łącznika usługi. Ta strona zawiera również domyślne nazwy zmiennych środowiskowych i wartości uzyskiwane podczas tworzenia połączenia z usługą.
Obsługiwane usługi obliczeniowe
Łącznik usługi może służyć do łączenia następujących usług obliczeniowych z usługą Azure Cosmos DB dla języka Apache Gremlin:
Azure App Service
Azure Container Apps
Azure Functions
Azure Kubernetes Service (AKS)
Azure Spring Apps
Obsługiwane typy uwierzytelniania i typy klientów
W poniższej tabeli pokazano, które kombinacje typów klientów i metod uwierzytelniania są obsługiwane do łączenia usługi obliczeniowej z usługą Azure Cosmos DB dla języka Apache Gremlin przy użyciu łącznika usługi. Wartość "Tak" wskazuje, że kombinacja jest obsługiwana, a wartość "Nie" wskazuje, że nie jest obsługiwana.
Typ klienta
Tożsamość zarządzana przypisana przez system
Tożsamość zarządzana przypisana przez użytkownika
Wpis tajny/parametry połączenia
Jednostka usługi
.NET
Tak
Tak
Tak
Tak
Java
Tak
Tak
Tak
Tak
Node.js
Tak
Tak
Tak
Tak
PHP
Tak
Tak
Tak
Tak
Python
Tak
Tak
Tak
Tak
Go
Tak
Tak
Tak
Tak
None
Tak
Tak
Tak
Tak
Ta tabela wskazuje, że obsługiwane są wszystkie kombinacje typów klientów i metod uwierzytelniania w tabeli. Wszystkie typy klientów mogą używać dowolnej metody uwierzytelniania do nawiązywania połączenia z usługą Azure Cosmos DB dla języka Apache Gremlin przy użyciu łącznika usługi.
Domyślne nazwy zmiennych środowiskowych lub właściwości aplikacji i przykładowy kod
Użyj poniższych szczegółów połączenia, aby połączyć usługi obliczeniowe z usługą Azure Cosmos DB dla języka Apache Gremlin. W każdym poniższym przykładzie zastąp tekst <Azure-Cosmos-DB-account>zastępczy , , <username><resource-group-name><collection or graphs><database><subscription-ID><client-ID><password><client-secret>i <tenant-id> własnymi informacjami. Aby uzyskać więcej informacji na temat konwencji nazewnictwa, zapoznaj się z artykułem Dotyczącym wewnętrznych łączników usług.
Tożsamość zarządzana przypisana przez system
Domyślna nazwa zmiennej środowiskowej
opis
Przykładowa wartość
AZURE_COSMOS_LISTKEYURL
Adres URL umożliwiający pobranie parametry połączenia
Zapoznaj się z poniższymi krokami i kodem, aby nawiązać połączenie z usługą Azure Cosmos DB dla języka Gremlin przy użyciu tożsamości zarządzanej przypisanej przez system.
Uzyskaj token dostępu dla tożsamości zarządzanej lub jednostki usługi przy użyciu biblioteki klienta Azure.Identity. Użyj tokenu dostępu i AZURE_COSMOS_LISTKEYURL pobierz hasło. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System;
using Gremlin.Net.Driver;
using Azure.Identity;
var gremlinEndpoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var gremlinPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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 Apache Gremlin
var server = new GremlinServer(
hostname: gremlinEndpoint,
port: gremlinPort,
username: userName,
password: password,
enableSsl: true
);
using var client = new GremlinClient(
gremlinServer: server,
messageSerializer: new Gremlin.Net.Structure.IO.GraphSON.GraphSON2MessageSerializer()
);
Uzyskaj token dostępu dla tożsamości zarządzanej lub jednostki usługi przy użyciu polecenia azure-identity. Użyj tokenu dostępu i AZURE_COSMOS_LISTKEYURL pobierz hasło. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
import java.net.URI;
int gremlinPort = Integer.parseInt(System.getenv("AZURE_COSMOS_PORT"));
String username = System.getenv("AZURE_COSMOS_USERNAME");
String gremlinEndpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listKeyUrl = System.getenv("AZURE_COSMOS_LISTKEYURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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 gremlinPassword = responseBody.get("primaryMasterKey");
// Connect to Azure Cosmos DB for Apache Gremlin
Cluster cluster;
Client client;
cluster = Cluster.addContactPoint(gremlinEndpoint).port(gremlinPort).credentials(username, password).create();
Instalowanie zależności.
pip install gremlinpython
Użyj polecenia azure-identity , aby uwierzytelnić się przy użyciu tożsamości zarządzanej lub jednostki usługi i wysłać żądanie w AZURE_COSMOS_LISTKEYURL celu uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
from gremlin_python.driver import client, serializer
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
username = os.getenv('AZURE_COSMOS_USERNAME')
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
port = os.getenv('AZURE_COSMOS_PORT')
listKeyUrl = os.getenv('AZURE_COSMOS_LISTKEYURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# 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_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 Apache Gremlin.
client = client.Client(
url=endpoint,
traversal_source="g",
username=username,
password=password,
message_serializer=serializer.GraphSONSerializersV2d0(),
)
Instalowanie zależności.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
W kodzie pobierz token dostępu przy użyciu metody azidentity, a następnie użyj go do uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennej środowiskowej dodanej przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
W kodzie pobierz token dostępu przy użyciu metody @azure/identity, a następnie użyj go do uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennej środowiskowej dodanej przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
import gremlin from 'gremlin'
const axios = require('axios');
let username = process.env.AZURE_COSMOS_USERNAME;
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let port = process.env.AZURE_COSMOS_PORT;
let listKeyUrl = process.env.AZURE_COSMOS_LISTKEYURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// 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_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'];
const credentials = new gremlin.driver.auth.PlainTextSaslAuthenticator(
username,
password
)
const client = new gremlin.driver.Client(
endpoint,
{
credentials,
traversalsource: 'g',
rejectUnauthorized: true,
mimeType: 'application/vnd.gremlin-v2.0+json'
}
)
client.open()
Uzyskaj token dostępu z tożsamością zarządzaną lub jednostką usługi, aby uzyskać klucz podstawowy usługi Azure Cosmos DB dla języka Gremlin, wywołując interfejs API REST pod adresem AZURE_COSMOS_LISTKEYURL.
W przypadku innych języków można użyć punktu końcowego Apache Gremlin i innych właściwości, które łącznik usługi ustawia na zmienne środowiskowe w celu nawiązania połączenia z zasobem usługi Azure Cosmos DB dla języka Apache Gremlin. Aby uzyskać szczegółowe informacje o zmiennej środowiskowej, zobacz Integrowanie usługi Azure Cosmos DB dla języka Apache Gremlin z łącznikiem usługi.
Tożsamość zarządzana przypisana przez użytkownika
Domyślna nazwa zmiennej środowiskowej
opis
Przykładowa wartość
AZURE_COSMOS_LISTKEYURL
Adres URL umożliwiający pobranie parametry połączenia
Zapoznaj się z poniższymi krokami i kodem, aby nawiązać połączenie z usługą Azure Cosmos DB dla języka Gremlin przy użyciu tożsamości zarządzanej przypisanej przez użytkownika.
Uzyskaj token dostępu dla tożsamości zarządzanej lub jednostki usługi przy użyciu biblioteki klienta Azure.Identity. Użyj tokenu dostępu i AZURE_COSMOS_LISTKEYURL pobierz hasło. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System;
using Gremlin.Net.Driver;
using Azure.Identity;
var gremlinEndpoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var gremlinPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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 Apache Gremlin
var server = new GremlinServer(
hostname: gremlinEndpoint,
port: gremlinPort,
username: userName,
password: password,
enableSsl: true
);
using var client = new GremlinClient(
gremlinServer: server,
messageSerializer: new Gremlin.Net.Structure.IO.GraphSON.GraphSON2MessageSerializer()
);
Uzyskaj token dostępu dla tożsamości zarządzanej lub jednostki usługi przy użyciu polecenia azure-identity. Użyj tokenu dostępu i AZURE_COSMOS_LISTKEYURL pobierz hasło. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
import java.net.URI;
int gremlinPort = Integer.parseInt(System.getenv("AZURE_COSMOS_PORT"));
String username = System.getenv("AZURE_COSMOS_USERNAME");
String gremlinEndpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listKeyUrl = System.getenv("AZURE_COSMOS_LISTKEYURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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 gremlinPassword = responseBody.get("primaryMasterKey");
// Connect to Azure Cosmos DB for Apache Gremlin
Cluster cluster;
Client client;
cluster = Cluster.addContactPoint(gremlinEndpoint).port(gremlinPort).credentials(username, password).create();
Instalowanie zależności.
pip install gremlinpython
Użyj polecenia azure-identity , aby uwierzytelnić się przy użyciu tożsamości zarządzanej lub jednostki usługi i wysłać żądanie w AZURE_COSMOS_LISTKEYURL celu uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
from gremlin_python.driver import client, serializer
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
username = os.getenv('AZURE_COSMOS_USERNAME')
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
port = os.getenv('AZURE_COSMOS_PORT')
listKeyUrl = os.getenv('AZURE_COSMOS_LISTKEYURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# 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_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 Apache Gremlin.
client = client.Client(
url=endpoint,
traversal_source="g",
username=username,
password=password,
message_serializer=serializer.GraphSONSerializersV2d0(),
)
Instalowanie zależności.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
W kodzie pobierz token dostępu przy użyciu metody azidentity, a następnie użyj go do uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennej środowiskowej dodanej przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
W kodzie pobierz token dostępu przy użyciu metody @azure/identity, a następnie użyj go do uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennej środowiskowej dodanej przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
import gremlin from 'gremlin'
const axios = require('axios');
let username = process.env.AZURE_COSMOS_USERNAME;
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let port = process.env.AZURE_COSMOS_PORT;
let listKeyUrl = process.env.AZURE_COSMOS_LISTKEYURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// 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_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'];
const credentials = new gremlin.driver.auth.PlainTextSaslAuthenticator(
username,
password
)
const client = new gremlin.driver.Client(
endpoint,
{
credentials,
traversalsource: 'g',
rejectUnauthorized: true,
mimeType: 'application/vnd.gremlin-v2.0+json'
}
)
client.open()
Uzyskaj token dostępu z tożsamością zarządzaną lub jednostką usługi, aby uzyskać klucz podstawowy usługi Azure Cosmos DB dla języka Gremlin, wywołując interfejs API REST pod adresem AZURE_COSMOS_LISTKEYURL.
W przypadku innych języków można użyć punktu końcowego Apache Gremlin i innych właściwości, które łącznik usługi ustawia na zmienne środowiskowe w celu nawiązania połączenia z zasobem usługi Azure Cosmos DB dla języka Apache Gremlin. Aby uzyskać szczegółowe informacje o zmiennej środowiskowej, zobacz Integrowanie usługi Azure Cosmos DB dla języka Apache Gremlin z łącznikiem usługi.
Connection string
Ostrzeżenie
Firma Microsoft zaleca korzystanie z najbezpieczniejszego dostępnego przepływu uwierzytelniania. Przepływ uwierzytelniania opisany w tej procedurze wymaga bardzo wysokiego poziomu zaufania w aplikacji i niesie ze sobą ryzyko, które nie występują w innych przepływach. Tego przepływu należy używać tylko wtedy, gdy inne bezpieczniejsze przepływy, takie jak tożsamości zarządzane, nie są opłacalne.
Domyślna nazwa zmiennej środowiskowej
opis
Przykładowa wartość
AZURE_COSMOS_HOSTNAME
Unikatowy identyfikator zasobu języka Gremlin (UFI)
Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin.
using System;
using Gremlin.Net.Driver;
var gremlinEndpoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var password = Environment.GetEnvironmentVariable("AZURE_COSMOS_PASSWORD");
var gremlinPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var server = new GremlinServer(
hostname: gremlinEndpoint,
port: gremlinPort,
username: userName,
password: password,
enableSsl: true
);
using var client = new GremlinClient(
gremlinServer: server,
messageSerializer: new Gremlin.Net.Structure.IO.GraphSON.GraphSON2MessageSerializer()
);
Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin.
Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin.
import os
from gremlin_python.driver import client, serializer
username = os.getenv('AZURE_COSMOS_USERNAME')
password = os.getenv('AZURE_COSMOS_PASSWORD')
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
port = os.getenv('AZURE_COSMOS_PORT')
client = client.Client(
url=endpoint,
traversal_source="g",
username=username,
password=password,
message_serializer=serializer.GraphSONSerializersV2d0(),
)
Zainstaluj zależność.
go get github.com/go-gremlin/gremlin
Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin.
Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin.
Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin.
W przypadku innych języków można użyć punktu końcowego Apache Gremlin i innych właściwości, które łącznik usługi ustawia na zmienne środowiskowe w celu nawiązania połączenia z zasobem usługi Azure Cosmos DB dla języka Apache Gremlin. Aby uzyskać szczegółowe informacje o zmiennej środowiskowej, zobacz Integrowanie usługi Azure Cosmos DB dla języka Apache Gremlin z łącznikiem usługi.
Jednostka usługi
Domyślna nazwa zmiennej środowiskowej
opis
Przykładowa wartość
AZURE_COSMOS_LISTKEYURL
Adres URL umożliwiający pobranie parametry połączenia
Uzyskaj token dostępu dla tożsamości zarządzanej lub jednostki usługi przy użyciu biblioteki klienta Azure.Identity. Użyj tokenu dostępu i AZURE_COSMOS_LISTKEYURL pobierz hasło. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System;
using Gremlin.Net.Driver;
using Azure.Identity;
var gremlinEndpoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
var gremlinPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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 Apache Gremlin
var server = new GremlinServer(
hostname: gremlinEndpoint,
port: gremlinPort,
username: userName,
password: password,
enableSsl: true
);
using var client = new GremlinClient(
gremlinServer: server,
messageSerializer: new Gremlin.Net.Structure.IO.GraphSON.GraphSON2MessageSerializer()
);
Uzyskaj token dostępu dla tożsamości zarządzanej lub jednostki usługi przy użyciu polecenia azure-identity. Użyj tokenu dostępu i AZURE_COSMOS_LISTKEYURL pobierz hasło. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
import java.net.URI;
int gremlinPort = Integer.parseInt(System.getenv("AZURE_COSMOS_PORT"));
String username = System.getenv("AZURE_COSMOS_USERNAME");
String gremlinEndpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listKeyUrl = System.getenv("AZURE_COSMOS_LISTKEYURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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 gremlinPassword = responseBody.get("primaryMasterKey");
// Connect to Azure Cosmos DB for Apache Gremlin
Cluster cluster;
Client client;
cluster = Cluster.addContactPoint(gremlinEndpoint).port(gremlinPort).credentials(username, password).create();
Instalowanie zależności.
pip install gremlinpython
Użyj polecenia azure-identity , aby uwierzytelnić się przy użyciu tożsamości zarządzanej lub jednostki usługi i wysłać żądanie w AZURE_COSMOS_LISTKEYURL celu uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennych środowiskowych dodanych przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
from gremlin_python.driver import client, serializer
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
username = os.getenv('AZURE_COSMOS_USERNAME')
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
port = os.getenv('AZURE_COSMOS_PORT')
listKeyUrl = os.getenv('AZURE_COSMOS_LISTKEYURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# 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_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 Apache Gremlin.
client = client.Client(
url=endpoint,
traversal_source="g",
username=username,
password=password,
message_serializer=serializer.GraphSONSerializersV2d0(),
)
Instalowanie zależności.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
W kodzie pobierz token dostępu przy użyciu metody azidentity, a następnie użyj go do uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennej środowiskowej dodanej przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
W kodzie pobierz token dostępu przy użyciu metody @azure/identity, a następnie użyj go do uzyskania hasła. Uzyskaj informacje o połączeniu ze zmiennej środowiskowej dodanej przez łącznik usługi i połącz się z usługą Azure Cosmos DB dla języka Apache Gremlin. Korzystając z poniższego kodu, usuń komentarz z części fragmentu kodu dla typu uwierzytelniania, którego chcesz użyć.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
import gremlin from 'gremlin'
const axios = require('axios');
let username = process.env.AZURE_COSMOS_USERNAME;
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let port = process.env.AZURE_COSMOS_PORT;
let listKeyUrl = process.env.AZURE_COSMOS_LISTKEYURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// 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_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'];
const credentials = new gremlin.driver.auth.PlainTextSaslAuthenticator(
username,
password
)
const client = new gremlin.driver.Client(
endpoint,
{
credentials,
traversalsource: 'g',
rejectUnauthorized: true,
mimeType: 'application/vnd.gremlin-v2.0+json'
}
)
client.open()
Uzyskaj token dostępu z tożsamością zarządzaną lub jednostką usługi, aby uzyskać klucz podstawowy usługi Azure Cosmos DB dla języka Gremlin, wywołując interfejs API REST pod adresem AZURE_COSMOS_LISTKEYURL.
W przypadku innych języków można użyć punktu końcowego Apache Gremlin i innych właściwości, które łącznik usługi ustawia na zmienne środowiskowe w celu nawiązania połączenia z zasobem usługi Azure Cosmos DB dla języka Apache Gremlin. Aby uzyskać szczegółowe informacje o zmiennej środowiskowej, zobacz Integrowanie usługi Azure Cosmos DB dla języka Apache Gremlin z łącznikiem usługi.
Następne kroki
Postępuj zgodnie z samouczkami wymienionymi poniżej, aby dowiedzieć się więcej o łączniku usługi.