簡體   English   中英

使用 Java SDK 的 Azure Cosmos DB Gremlin/Tinkerpop 令牌身份驗證

[英]Azure Cosmos DB Gremlin/Tinkerpop Token Auth with Java SDK

我正在嘗試使用資源令牌連接到 Azure Cosmos DB 中的 Gremlin 集合。 我從這里改編了文檔(主要用於 C#): https : //docs.microsoft.com/en-us/azure/cosmos-db/how-to-use-resource-tokens-gremlin

問題是,一旦我嘗試訪問數據,令牌的日期標頭似乎無效:

Exception in thread "main" java.util.concurrent.CompletionException: org.apache.tinkerpop.gremlin.driver.exception.ResponseException: 

ActivityId : 00000000-0000-0000-0000-000000000000
ExceptionType : UnauthorizedException
ExceptionMessage :
    The input date header is invalid format. Please pass in RFC 1123 style date format.
    ActivityId: 755ab024-fc79-47a3-bc44-3231b2db7dc1, documentdb-dotnet-sdk/2.7.0 Host/64-bit MicrosoftWindowsNT/6.2.9200.0
Source : Microsoft.Azure.Documents.ClientThe input date header is invalid format. Please pass in RFC 1123 style date format.
ActivityId: 755ab024-fc79-47a3-bc44-3231b2db7dc1, documentdb-dotnet-sdk/2.7.0 Host/64-bit MicrosoftWindowsNT/6.2.9200.0
    BackendStatusCode : Unauthorized
    BackendActivityId : 755ab024-fc79-47a3-bc44-3231b2db7dc1
    HResult : 0x80131500

有誰知道如何解決這個問題? 通過-Duser.timezone=GMT將 JVM 設置為-Duser.timezone=GMT

這是代碼。 請注意,它是一個 Java CLI 應用程序,僅用於測試連接性。 cfg所有數據基本上都是由 cli 給出的,方法名稱應該是不言自明的。

令牌生成,這是使用DocumentClient實例的主密鑰:

...
import com.microsoft.azure.documentdb.DocumentClient;
import com.microsoft.azure.documentdb.DocumentClientException;
import com.microsoft.azure.documentdb.FeedResponse;
import com.microsoft.azure.documentdb.Permission;
import com.microsoft.azure.documentdb.PermissionMode;
import com.microsoft.azure.documentdb.ResourceResponse;
import com.microsoft.azure.documentdb.User;
...

public class TokenGenerator {

    private String USER_ID = "demo-1";

    public String generateToken(CmdLineConfiguration cfg) throws DocumentClientException {
        try (DocumentClient client = Utilities.documentClientFrom(cfg)) {
            String databaseLink = String.format("/dbs/%s", cfg.getDatabaseId());
            String collectionLink = String.format("/dbs/%s/colls/%s", cfg.getDatabaseId(), cfg.getCollectionId());

            // get all users within database
            FeedResponse<User> queryResults = client.readUsers(databaseLink, null);
            List<User> onlineUsers = queryResults.getQueryIterable().toList();

            // if a user exists, grab the first one, if not create it
            User user;
            Optional<User> onlineUser = onlineUsers.stream().filter(u -> u.getId().equals(USER_ID)).findFirst();
            if (onlineUser.isPresent()) {
                user = onlineUser.get();
            } else {
                User u = new User();
                u.setId(USER_ID);
                ResourceResponse<User> generatedUser = client.createUser(databaseLink, u, null);
                user = generatedUser.getResource();
            }

            // read permissions, if existent use, else create
            FeedResponse<Permission> permissionResponse = client.readPermissions(user.getSelfLink(), null);
            List<Permission> onlinePermissions = permissionResponse.getQueryIterable().toList();
            Permission permission;
            if (onlinePermissions.size() == 0) {
                Permission p = new Permission();
                p.setPermissionMode(PermissionMode.Read);
                p.setId(USER_ID + "_READ");
                p.setResourceLink(collectionLink);
                ResourceResponse<Permission> generatedPermission = client.createPermission(user.getSelfLink(), p, null);
                permission = generatedPermission.getResource();
            } else {
                permission = onlinePermissions.get(0);
            }
            // return the token
            return permission.getToken();
        }
    }
}

連接和查詢 Gremlin:

...
import org.apache.tinkerpop.gremlin.driver.AuthProperties;
import org.apache.tinkerpop.gremlin.driver.AuthProperties.Property;
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import org.apache.tinkerpop.gremlin.driver.ResultSet;
...


        Cluster cluster;
        String collectionLink = String.format("/dbs/%s/colls/%s", cfg.getDatabaseId(), cfg.getCollectionId());
        TokenGenerator tg = new TokenGenerator();
        String token = tg.generateToken(cfg);

        Cluster.Builder builder = Cluster.build(new File("src/remote.yaml"));
        AuthProperties authenticationProperties = new AuthProperties();
        authenticationProperties.with(AuthProperties.Property.USERNAME, collectionLink);

        authenticationProperties.with(Property.PASSWORD, token);
        builder.authProperties(authenticationProperties);
        cluster = builder.create();

        Client client = cluster.connect();
        ResultSet results = client.submit("g.V().limit(1)");

        // the following call fails
        results.stream().forEach(System.out::println);

        client.close();
        cluster.close();
    }

src/remote.yml

hosts: [COSMOSNAME.gremlin.cosmosdb.azure.com]
port: 443
username: /dbs/DBNAME/colls/COLLECTIONNAME
connectionPool: { enableSsl: true}
serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV2d0, config: { serializeResultToString: true }}

我無法在我這邊重現您的問題。 我試圖為java擴展這個宇宙圖演示。在那個演示中,使用了主密鑰,所以我按照你的部分代碼和官方示例來訪問帶有資源令牌的圖數據庫。

您與 db 的連接代碼似乎有效。我的主類如下,與您的類似:

import org.apache.tinkerpop.gremlin.driver.*;
import org.apache.tinkerpop.gremlin.driver.exception.ResponseException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


public class Program
{
        static final String gremlinQueries[] = new String[] {"g.V().limit(1)"};

  public static void main( String[] args ) throws ExecutionException, InterruptedException {

        String token = "***";
        Cluster cluster;
        Client client;

        try {
            Cluster.Builder builder = Cluster.build(new File("src/remote.yaml"));
//            Cluster.Builder builder = Cluster.build();
            AuthProperties authenticationProperties = new AuthProperties();
            authenticationProperties.with(AuthProperties.Property.USERNAME,
                    String.format("/dbs/%s/colls/%s", "db", "coll"));

// The format of the token is "type=resource&ver=1&sig=<base64 string>;<base64 string>;".
            authenticationProperties.with(AuthProperties.Property.PASSWORD, token);

            builder.authProperties(authenticationProperties);

            // Attempt to create the connection objects
            cluster = builder.create();
//            cluster = Cluster.build(new File("src/remote.yaml")).create();
            client = cluster.connect();
        } catch (Exception e) {
            // Handle file errors.
            System.out.println("Couldn't find the configuration file.");
            e.printStackTrace();
            return;
        }

        // After connection is successful, run all the queries against the server.
        for (String query : gremlinQueries) {
            System.out.println("\nSubmitting this Gremlin query: " + query);

            // Submitting remote query to the server.
            ResultSet results = client.submit(query);

            CompletableFuture<List<Result>> completableFutureResults;
            CompletableFuture<Map<String, Object>> completableFutureStatusAttributes;
            List<Result> resultList;
            Map<String, Object> statusAttributes;

            try{
                completableFutureResults = results.all();
                completableFutureStatusAttributes = results.statusAttributes();
                resultList = completableFutureResults.get();
                statusAttributes = completableFutureStatusAttributes.get();            
            }
            catch(ExecutionException | InterruptedException e){
                e.printStackTrace();
                break;
            }
            catch(Exception e){
                ResponseException re = (ResponseException) e.getCause();

                // Response status codes. You can catch the 429 status code response and work on retry logic.
                System.out.println("Status code: " + re.getStatusAttributes().get().get("x-ms-status-code")); 
                System.out.println("Substatus code: " + re.getStatusAttributes().get().get("x-ms-substatus-code")); 

                // If error code is 429, this value will inform how many milliseconds you need to wait before retrying.
                System.out.println("Retry after (ms): " + re.getStatusAttributes().get().get("x-ms-retry-after"));

                // Total Request Units (RUs) charged for the operation, upon failure.
                System.out.println("Request charge: " + re.getStatusAttributes().get().get("x-ms-total-request-charge"));

                // ActivityId for server-side debugging
                System.out.println("ActivityId: " + re.getStatusAttributes().get().get("x-ms-activity-id"));
                throw(e);
            }

            for (Result result : resultList) {
                System.out.println("\nQuery result:");
                System.out.println(result.toString());
            }

            // Status code for successful query. Usually HTTP 200.
            System.out.println("Status: " + statusAttributes.get("x-ms-status-code").toString());

            // Total Request Units (RUs) charged for the operation, after a successful run.
            System.out.println("Total charge: " + statusAttributes.get("x-ms-total-request-charge").toString());
        }

        System.out.println("Demo complete!\n Press Enter key to continue...");
        try{
            System.in.read();
        } catch (IOException e){
            e.printStackTrace();
            return;
        }

        // Properly close all opened clients and the cluster
        cluster.close();

        System.exit(0);
    }
}

yaml 文件:

hosts: [***.gremlin.cosmosdb.azure.com]
port: 443
username: /dbs/db/colls/coll

connectionPool: {
  enableSsl: true}
serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV2d0, config: { serializeResultToString: true }}

所以,恐怕根本原因是代幣的產生。

輸入日期標題格式無效。 請傳入 RFC 1123 樣式的日期格式。

我搜索了這個與 cosmos db 相關的錯誤消息,我找到了這個案例供您參考。似乎解決方案正在更改本地區域設置。您可以使用 Fiddler 跟蹤請求的x-ms-date標頭。

通過 Azure 支持,我發現問題是 Azure 方面的一個錯誤。 將自定義 VNet 與 Cosmos 一起使用時會發生這種情況。 與此同時,Azure 已經修復了它,一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM