如何使用 Microsoft Graph API 通过 Java 使用 HttpURLConnection 通过 appId 获取应用程序

How to GET application by appId using Microsoft Graph API via Java using HttpURLConnection

我想授权 Azure Active Directory 授予的 OAuth JSON Web 令牌,我需要做的一件事是使用 Microsoft Graph [=37= 在令牌的 appId 中获取有关应用程序的更多信息].

Microsoft Graph API 允许我通过

通过其 ID 获取应用程序
https://graph.microsoft.com/beta/applications/{id}

,但不是通过

的 appId
https://graph.microsoft.com/beta/applications/{appId}

我看到使用 Microsoft Graph API 获取应用程序的最佳方法是通过过滤器,如下所示:

https://graph.microsoft.com/beta/applications?filter=appId eq '{appId}'

上面的过滤器在 Microsoft Graph Explorer 中工作得很好,但是当使用 HttpUrlConnection 使用 GET 请求调用 Graph API 时,我的请求失败并显示 HTTP 代码 400 和消息 "Bad Request"。

这很奇怪,因为使用完全相同的 HttpUrlConnection 通过

获取所有应用程序
https://graph.microsoft.com/beta/applications

工作正常。

我无法在 Microsoft Graph API GET 请求中使用筛选器功能吗?我应该如何通过其 AppId 获取有关应用程序的信息?

这是我用于 HttpURLConnection 的 Java 代码片段:

url = new URL(String.format("https://graph.microsoft.com/beta/applications?filter=appId eq '%s'", appId));
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Bearer " + result.getAccessToken());
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Content-Type", "application/json");

        final int httpResponseCode = conn.getResponseCode();
        if (httpResponseCode == 200 || httpResponseCode == 201) {
            BufferedReader in = null;
            final StringBuilder response;
            try {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String inputLine;
                response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            } finally {
                in.close();
            }
            final JSONObject json = new JSONObject(response.toString());
            return json.toString(4);
        } else {
            return String.format("Connection returned HTTP code: %s with message: %s",
                    httpResponseCode, conn.getResponseMessage());
        }

您应该对查询参数进行 URLEncode。

String url2=URLEncoder.encode("$filter=appId eq '{applicationId}'");
URL url = new URL("https://graph.microsoft.com/beta/applications?"+url2);

万一其他人来找这个,如果您使用的是 GraphServiceClient,您可以这样做:

var appId = "some app id";

var response = await _graphClient.Applications
    .Request()
    .Filter($"appId eq '{appId}'")
    .GetAsync();

var azureAddApplication = response.FirstOrDefault() ?? throw new ArgumentException($"Couldn't find App registration with app id {appId}");