이 페이지에는 지원되는 인증 방법 및 클라이언트가 표시되며, 서비스 커넥터를 사용하여 Azure Cosmos DB for Apache Gremlin을 다른 클라우드 서비스에 연결하는 데 사용할 수 있는 샘플 코드가 표시됩니다. 서비스 커넥터를 사용하지 않고 다른 프로그래밍 언어로 Azure Cosmos DB for Gremlin에 계속 연결할 수 있습니다. 이 페이지에서는 서비스 연결을 만들 때 가져오는 기본 환경 변수 이름과 값도 보여 줍니다.
지원되는 컴퓨팅 서비스
서비스 커넥터를 사용하여 다음 컴퓨팅 서비스를 Azure Cosmos DB for Apache Gremlin에 연결할 수 있습니다.
- Azure App Service
- Azure Container Apps
- Azure 기능
- AKS(Azure Kubernetes Service)
- Azure Spring Apps
지원되는 인증 유형 및 클라이언트 유형
아래 표에서는 서비스 커넥터를 사용하여 컴퓨팅 서비스를 Azure Cosmos DB for Apache Gremlin에 연결하는 데 지원되는 클라이언트 유형 및 인증 방법의 조합을 보여 줍니다. "예"는 조합이 지원됨을 나타내고 "아니오"는 지원되지 않음을 나타냅니다.
클라이언트 유형 |
시스템 할당 관리 ID |
사용자 할당 관리 ID |
비밀/연결 문자열 |
서비스 사용자 |
.NET |
예 |
예 |
예 |
예 |
Java |
예 |
예 |
예 |
예 |
Node.JS |
예 |
예 |
예 |
예 |
PHP |
예 |
예 |
예 |
예 |
Python |
예 |
예 |
예 |
예 |
Go |
예 |
예 |
예 |
예 |
없음 |
예 |
예 |
예 |
예 |
이 표는 표에 있는 클라이언트 유형과 모든 인증 방법 조합이 지원됨을 나타냅니다. 모든 클라이언트 유형은 어느 인증 방법으로나 서비스 커넥터를 사용하여 Azure Cosmos DB for Apache Gremlin에 연결할 수 있습니다.
기본 환경 변수 이름 또는 애플리케이션 속성과 샘플 코드
아래 연결 세부 정보를 사용하여 컴퓨팅 서비스를 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래의 각 예제에서 자리 표시자 텍스트 <Azure-Cosmos-DB-account>
, <database>
, <collection or graphs>
, <username>
, <password>
, <resource-group-name>
, <subscription-ID>
, <client-ID>
, <client-secret>
및 <tenant-id>
를 고유의 정보로 바꿉니다. 명명 규칙에 대한 자세한 내용은 서비스 커넥터 내부 문서를 참조하세요.
시스템 할당 관리 ID
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_COSMOS_LISTKEYURL |
연결 문자열을 가져올 URL |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-account>/listKeys?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
관리 ID 범위 |
https://management.azure.com/.default |
AZURE_COSMOS_RESOURCEENDPOINT |
리소스 엔드포인트 |
https://<Azure-Cosmos-DB-account>.documents.azure.com:443/ |
AZURE_COSMOS_HOSTNAME |
Gremlin UFI(고유 리소스 식별자) |
<Azure-Cosmos-DB-account>.gremlin.cosmos.azure.com |
AZURE_COSMOS_PORT |
연결 포트 |
443 |
AZURE_COSMOS_USERNAME |
사용자 이름 |
/dbs/<database>/colls/<collection or graphs> |
샘플 코드
시스템이 할당한 관리 ID를 사용하여 Azure Cosmos DB for Gremlin에 연결하려면 아래 단계 및 코드를 참조하세요.
종속성을 설치합니다.
dotnet add package Gremlin.Net
dotnet add package Azure.Identity
클라이언트 라이브러리 Azure.Identity를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 AZURE_COSMOS_LISTKEYURL
을 사용하여 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
);
pom.xml 파일에서 다음 종속성을 추가합니다.
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-driver</artifactId>
<version>3.4.13</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 AZURE_COSMOS_LISTKEYURL
을 사용하여 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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();
종속성을 설치합니다.
pip install gremlinpython
azure-identity
를 사용하여 관리 ID 또는 서비스 주체로 인증하고 AZURE_COSMOS_LISTKEYURL
에 요청을 보내 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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(),
)
종속성을 설치합니다.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
코드에서 azidentity
를 사용하여 액세스 토큰을 가져오고 이 토큰을 사용하여 암호를 얻습니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"github.com/go-gremlin/gremlin"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
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 identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listKeyUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
password, err := result["primaryMasterKey"];
auth := gremlin.OptAuthUserPass(username, password)
client, err := gremlin.NewClient(endpoint, auth)
}
종속성을 설치합니다.
npm install gremlin
npm install --save @azure/identity
코드에서 @azure/identity
를 사용하여 액세스 토큰을 가져오고 이 토큰을 사용하여 암호를 얻습니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
관리 ID 또는 서비스 주체를 사용하여 액세스 토큰을 가져와 AZURE_COSMOS_LISTKEYURL
에서 REST API를 호출하여 Azure Cosmos DB for Gremlin의 기본 키를 획득합니다.
$endpoint = getenv('AZURE_COSMOS_RESOURCEENDPOINT');
$username = getenv('AZURE_COSMOS_USERNAME');
$port = getenv('AZURE_COSMOS_PORT');
$db = new Connection([
'host' => $endpoint,
'username' => $username,
'password' => $password,
'port' => $port,
'ssl' => TRUE
]);
사용자 할당 관리 ID
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_COSMOS_LISTKEYURL |
연결 문자열을 가져올 URL |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-account>/listKeys?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
관리 ID 범위 |
https://management.azure.com/.default |
AZURE_COSMOS_RESOURCEENDPOINT |
리소스 엔드포인트 |
https://<Azure-Cosmos-DB-account>.documents.azure.com:443/ |
AZURE_COSMOS_HOSTNAME |
Gremlin UFI(고유 리소스 식별자) |
<Azure-Cosmos-DB-account>.gremlin.cosmos.azure.com |
AZURE_COSMOS_PORT |
연결 포트 |
443 |
AZURE_COSMOS_USERNAME |
사용자 이름 |
/dbs/<database>/colls/<collection or graphs> |
AZURE_CLIENTID |
클라이언트 ID |
<client_ID> |
샘플 코드
사용자가 할당한 관리 ID를 사용하여 Azure Cosmos DB for Gremlin에 연결하려면 아래 단계 및 코드를 참조하세요.
종속성을 설치합니다.
dotnet add package Gremlin.Net
dotnet add package Azure.Identity
클라이언트 라이브러리 Azure.Identity를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 AZURE_COSMOS_LISTKEYURL
을 사용하여 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
);
pom.xml 파일에서 다음 종속성을 추가합니다.
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-driver</artifactId>
<version>3.4.13</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 AZURE_COSMOS_LISTKEYURL
을 사용하여 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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();
종속성을 설치합니다.
pip install gremlinpython
azure-identity
를 사용하여 관리 ID 또는 서비스 주체로 인증하고 AZURE_COSMOS_LISTKEYURL
에 요청을 보내 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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(),
)
종속성을 설치합니다.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
코드에서 azidentity
를 사용하여 액세스 토큰을 가져오고 이 토큰을 사용하여 암호를 얻습니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"github.com/go-gremlin/gremlin"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
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 identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listKeyUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
password, err := result["primaryMasterKey"];
auth := gremlin.OptAuthUserPass(username, password)
client, err := gremlin.NewClient(endpoint, auth)
}
종속성을 설치합니다.
npm install gremlin
npm install --save @azure/identity
코드에서 @azure/identity
를 사용하여 액세스 토큰을 가져오고 이 토큰을 사용하여 암호를 얻습니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
관리 ID 또는 서비스 주체를 사용하여 액세스 토큰을 가져와 AZURE_COSMOS_LISTKEYURL
에서 REST API를 호출하여 Azure Cosmos DB for Gremlin의 기본 키를 획득합니다.
$endpoint = getenv('AZURE_COSMOS_RESOURCEENDPOINT');
$username = getenv('AZURE_COSMOS_USERNAME');
$port = getenv('AZURE_COSMOS_PORT');
$db = new Connection([
'host' => $endpoint,
'username' => $username,
'password' => $password,
'port' => $port,
'ssl' => TRUE
]);
Connection string
Warning
사용 가능한 가장 안전한 인증 흐름을 사용하는 것이 권장됩니다. 이 절차에서 설명된 인증 흐름은 다른 흐름에는 없는 위험을 전달하며, 애플리케이션에서 매우 높은 신뢰 수준을 요구합니다. 이 흐름은 관리 ID와 같은 보다 안전한 다른 흐름을 실행할 수 없는 경우에만 사용되어야 합니다.
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_COSMOS_HOSTNAME |
Gremlin UFI(고유 리소스 식별자) |
<Azure-Cosmos-DB-account>.gremlin.cosmos.azure.com |
AZURE_COSMOS_PORT |
연결 포트 |
443 |
AZURE_COSMOS_USERNAME |
사용자 이름 |
/dbs/<database>/colls/<collection or graphs> |
AZURE_COSMOS_PASSWORD |
암호 |
<password> |
샘플 코드
연결 문자열을 사용하여 Azure Cosmos DB for Gremlin에 연결하려면 아래 단계 및 코드를 참조하세요.
종속성을 설치합니다.
dotnet add package Gremlin.Net
서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 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()
);
pom.xml 파일에 다음 종속성을 추가합니다.
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-driver</artifactId>
<version>3.4.13</version>
</dependency>
서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다.
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
int gremlinPort = Integer.parseInt(System.getenv("AZURE_COSMOS_PORT"));
String username = System.getenv("AZURE_COSMOS_USERNAME");
String gremlinEndpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String password = System.getenv("AZURE_COSMOS_PASSWORD");
Cluster cluster;
Client client;
cluster = Cluster.addContactPoint(gremlinEndpoint).port(gremlinPort).credentials(username, password).create();
종속성을 설치합니다.
pip install gremlinpython
서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for 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(),
)
- 종속성을 설치합니다.
go get github.com/go-gremlin/gremlin
- 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다.
username = os.Getenv("AZURE_COSMOS_USERNAME")
password = os.getenv("AZURE_COSMOS_PASSWORD")
endpoint = os.getenv("AZURE_COSMOS_RESOURCEENDPOINT")
port = os.getenv("AZURE_COSMOS_PORT")
auth := gremlin.OptAuthUserPass(username, password)
client, err := gremlin.NewClient(endpoint, auth)
- 종속성을 설치합니다.
npm install gremlin
- 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다.
import gremlin from 'gremlin'
const username = process.env.AZURE_COSMOS_USERNAME;
const password = process.env.AZURE_COSMOS_PASSWORD;
const endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
const port = process.env.AZURE_COSMOS_PORT;
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()
서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다.
$endpoint = getenv('AZURE_COSMOS_RESOURCEENDPOINT');
$username = getenv('AZURE_COSMOS_USERNAME');
$password = getenv('AZURE_COSMOS_PASSWORD');
$port = getenv('AZURE_COSMOS_PORT');
$db = new Connection([
'host' => $endpoint,
'username' => $username,
'password' => $password,
'port' => $port,
'ssl' => TRUE
]);
서비스 사용자
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_COSMOS_LISTKEYURL |
연결 문자열을 가져올 URL |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-account>/listKeys?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
관리 ID 범위 |
https://management.azure.com/.default |
AZURE_COSMOS_RESOURCEENDPOINT |
리소스 엔드포인트 |
https://<Azure-Cosmos-DB-account>.documents.azure.com:443/ |
AZURE_COSMOS_HOSTNAME |
Gremlin UFI(고유 리소스 식별자) |
<Azure-Cosmos-DB-account>.gremlin.cosmos.azure.com |
AZURE_COSMOS_PORT |
Gremlin 연결 포트 |
10350 |
AZURE_COSMOS_USERNAME |
사용자 이름 |
</dbs/<database>/colls/<collection or graphs> |
AZURE_COSMOS_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_COSMOS_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_COSMOS_TENANTID |
테넌트 ID |
<tenant-ID> |
샘플 코드
서비스 주체를 사용하여 Gremlin용 Azure Cosmos DB에 연결하려면 아래 단계 및 코드를 참조하세요.
종속성을 설치합니다.
dotnet add package Gremlin.Net
dotnet add package Azure.Identity
클라이언트 라이브러리 Azure.Identity를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 AZURE_COSMOS_LISTKEYURL
을 사용하여 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
);
pom.xml 파일에서 다음 종속성을 추가합니다.
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-driver</artifactId>
<version>3.4.13</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 AZURE_COSMOS_LISTKEYURL
을 사용하여 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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();
종속성을 설치합니다.
pip install gremlinpython
azure-identity
를 사용하여 관리 ID 또는 서비스 주체로 인증하고 AZURE_COSMOS_LISTKEYURL
에 요청을 보내 암호를 가져옵니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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(),
)
종속성을 설치합니다.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/go-gremlin/gremlin
코드에서 azidentity
를 사용하여 액세스 토큰을 가져오고 이 토큰을 사용하여 암호를 얻습니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"github.com/go-gremlin/gremlin"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
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 identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listKeyUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
password, err := result["primaryMasterKey"];
auth := gremlin.OptAuthUserPass(username, password)
client, err := gremlin.NewClient(endpoint, auth)
}
종속성을 설치합니다.
npm install gremlin
npm install --save @azure/identity
코드에서 @azure/identity
를 사용하여 액세스 토큰을 가져오고 이 토큰을 사용하여 암호를 얻습니다. 서비스 커넥터에서 추가한 환경 변수에서 연결 정보를 가져와 Azure Cosmos DB for Apache Gremlin에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
관리 ID 또는 서비스 주체를 사용하여 액세스 토큰을 가져와 AZURE_COSMOS_LISTKEYURL
에서 REST API를 호출하여 Azure Cosmos DB for Gremlin의 기본 키를 획득합니다.
$endpoint = getenv('AZURE_COSMOS_RESOURCEENDPOINT');
$username = getenv('AZURE_COSMOS_USERNAME');
$port = getenv('AZURE_COSMOS_PORT');
$db = new Connection([
'host' => $endpoint,
'username' => $username,
'password' => $password,
'port' => $port,
'ssl' => TRUE
]);
다음 단계
서비스 커넥터에 대해 자세히 알아보려면 아래 나열된 자습서를 따르세요.