Integrate the Azure Cosmos DB for Gremlin with Service Connector
Artikkeli
This page shows supported authentication methods and clients, and shows sample code you can use to connect Azure Cosmos DB for Apache Gremlin to other cloud services using Service Connector. You might still be able to connect to Azure Cosmos DB for Gremlin in other programming languages without using Service Connector. This page also shows default environment variable names and values you get when you create the service connection.
Supported compute services
Service Connector can be used to connect the following compute services to Azure Cosmos DB for Apache Gremlin:
Azure App Service
Azure Container Apps
Azure Functions
Azure Kubernetes Service (AKS)
Azure Spring Apps
Supported authentication types and client types
The table below shows which combinations of client types and authentication methods are supported for connecting your compute service to Azure Cosmos DB for Apache Gremlin using Service Connector. A “Yes” indicates that the combination is supported, while a “No” indicates that it is not supported.
Client type
System-assigned managed identity
User-assigned managed identity
Secret / connection string
Service principal
.NET
Yes
Yes
Yes
Yes
Java
Yes
Yes
Yes
Yes
Node.js
Yes
Yes
Yes
Yes
PHP
Yes
Yes
Yes
Yes
Python
Yes
Yes
Yes
Yes
Go
Yes
Yes
Yes
Yes
None
Yes
Yes
Yes
Yes
This table indicates that all combinations of client types and authentication methods in the table are supported. All client types can use any of the authentication methods to connect to Azure Cosmos DB for Apache Gremlin using Service Connector.
Default environment variable names or application properties and sample code
Use the connection details below to connect your compute services to Azure Cosmos DB for Apache Gremlin. For each example below, replace the placeholder texts <Azure-Cosmos-DB-account>, <database>, <collection or graphs>, <username>, <password>, <resource-group-name>, <subscription-ID>, <client-ID>,<client-secret>, and <tenant-id> with your own information. For more information about naming conventions, check the Service Connector internals article.
Get an access token for the managed identity or service principal using client library Azure.Identity. Use the access token and AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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()
);
Add the following dependencies in your pom.xml file:
Get an access token for the managed identity or service principal using azure-identity. Use the access token and AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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();
Install dependencies.
pip install gremlinpython
Use azure-identity to authenticate with the managed identity or service principal and send request to AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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(),
)
Install dependencies.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
In code, get the access token using azidentity, then use it to acquire the password. Get connection information from the environment variable added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
In code, get the access token using @azure/identity, then use it to acquire the password. Get connection information from the environment variable added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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()
Get an access token with a managed identity or a service principal to acquire the primary key of Azure Cosmos DB for Gremlin by calling REST API at AZURE_COSMOS_LISTKEYURL.
For other languages, you can use the Apache Gremlin endpoint and other properties that Service Connector sets to the environment variables to connect to Azure Cosmos DB for Apache Gremlin resource. For environment variable details, see Integrate Azure Cosmos DB for Apache Gremlin with Service Connector.
Get an access token for the managed identity or service principal using client library Azure.Identity. Use the access token and AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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()
);
Add the following dependencies in your pom.xml file:
Get an access token for the managed identity or service principal using azure-identity. Use the access token and AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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();
Install dependencies.
pip install gremlinpython
Use azure-identity to authenticate with the managed identity or service principal and send request to AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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(),
)
Install dependencies.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
In code, get the access token using azidentity, then use it to acquire the password. Get connection information from the environment variable added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
In code, get the access token using @azure/identity, then use it to acquire the password. Get connection information from the environment variable added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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()
Get an access token with a managed identity or a service principal to acquire the primary key of Azure Cosmos DB for Gremlin by calling REST API at AZURE_COSMOS_LISTKEYURL.
For other languages, you can use the Apache Gremlin endpoint and other properties that Service Connector sets to the environment variables to connect to Azure Cosmos DB for Apache Gremlin resource. For environment variable details, see Integrate Azure Cosmos DB for Apache Gremlin with Service Connector.
Connection string
Warning
Microsoft recommends that you use the most secure authentication flow available. The authentication flow described in this procedure requires a very high degree of trust in the application, and carries risks that are not present in other flows. You should only use this flow when other more secure flows, such as managed identities, aren't viable.
Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for 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()
);
Add the following dependency in your pom.xml file:
For other languages, you can use the Apache Gremlin endpoint and other properties that Service Connector sets to the environment variables to connect to Azure Cosmos DB for Apache Gremlin resource. For environment variable details, see Integrate Azure Cosmos DB for Apache Gremlin with Service Connector.
Get an access token for the managed identity or service principal using client library Azure.Identity. Use the access token and AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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()
);
Add the following dependencies in your pom.xml file:
Get an access token for the managed identity or service principal using azure-identity. Use the access token and AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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();
Install dependencies.
pip install gremlinpython
Use azure-identity to authenticate with the managed identity or service principal and send request to AZURE_COSMOS_LISTKEYURL to get the password. Get the connection information from the environment variables added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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(),
)
Install dependencies.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
In code, get the access token using azidentity, then use it to acquire the password. Get connection information from the environment variable added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
In code, get the access token using @azure/identity, then use it to acquire the password. Get connection information from the environment variable added by Service Connector and connect to Azure Cosmos DB for Apache Gremlin. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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()
Get an access token with a managed identity or a service principal to acquire the primary key of Azure Cosmos DB for Gremlin by calling REST API at AZURE_COSMOS_LISTKEYURL.
For other languages, you can use the Apache Gremlin endpoint and other properties that Service Connector sets to the environment variables to connect to Azure Cosmos DB for Apache Gremlin resource. For environment variable details, see Integrate Azure Cosmos DB for Apache Gremlin with Service Connector.
Next steps
Follow the tutorials listed below to learn more about Service Connector.