简体   繁体   English

使用 Java 从 AAD 访问 MS Graph 用户数据

[英]MS Graph User Data Access from AAD using Java

I am trying to access MS Graph for an AAD account using Java. It is to fetch all User Data.我正在尝试使用 Java 访问 AAD 帐户的 MS Graph。它是为了获取所有用户数据。 When trying to access MS Graph I get 401 error:尝试访问 MS Graph 时出现 401 错误:

            ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                            Collections.singleton("https://graph.microsoft.com/.default"))
                    .build();

            CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);

            URL url = new URL("https://graph.microsoft.com/v1.0/users");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + future.get());
            conn.setRequestProperty("Accept","application/json");

            int httpResponseCode = conn.getResponseCode();
            if(httpResponseCode == HTTPResponse.SC_OK) {

                try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        responseString.append(inputLine);
                    }
                }
            }
          return responseString.toString();

Scope and other permissions are given.给了Scope等权限。 I am getting following result.我得到以下结果。 Hope anyone can guide me to resolve the issue.希望任何人都可以指导我解决问题。

This is my latest code.这是我的最新代码。 I used the function getAccessTokenByClientCredentialGrant to fetch access token and called the GET api call manually by adding access token to the header. Using graph client is the best practice as of my knowdeldge.我使用 function getAccessTokenByClientCredentialGrant来获取访问令牌,并通过将访问令牌添加到 header 来手动调用 GET api 调用。根据我的知识,使用图形客户端是最佳实践。

            String CLIENT_ID = "{{ClientId}}";
            String CLIENT_SECRET = "{{ClientSecret}}";
            String AUTHORITY = "https://login.microsoftonline.com/{{TenantId}}";
            Set<String> SCOPE = Collections.singleton("https://graph.microsoft.com/.default");
        try {

            String access_token = getAccessTokenByClientCredentialGrant(CLIENT_ID, CLIENT_SECRET,
                    AUTHORITY, SCOPE).accessToken();

            URL url = new URL("https://graph.microsoft.com/v1.0/users");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "Bearer " + access_token);
            conn.setRequestProperty("Accept","application/json");

            int httpResponseCode = conn.getResponseCode();
            JsonPointer responseString = null;
            if(httpResponseCode == HTTPResponse.SC_OK) {

                try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                       response.put(RESULT, responseString.toString());
                    }
                }
            }
          
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Response "+responseString);

And getAccessTokenByClientCredentialGrant function goes like this: getAccessTokenByClientCredentialGrant function 是这样的:

 private IAuthenticationResult getAccessTokenByClientCredentialGrant(String client_id, String client_secret, String authority, Set<String> scope) throws MalformedURLException, ExecutionException, InterruptedException {
    ConfidentialClientApplication app = ConfidentialClientApplication
            .builder(client_id, ClientCredentialFactory
                    .createFromSecret(client_secret))
            .authority(authority).build();

    ClientCredentialParameters clientCredentialParam = ClientCredentialParameters
            .builder(scope).build();

    CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
    return future.get();
}

Suggested readings: https://blogs.aaddevsup.xyz/2021/08/microsoft-graph-why-you-cannot-call-the-me-endpoint-with-a-token-acquired-via-the-client-credentials-grant-flow/建议阅读: https://blogs.aaddevsup.xyz/2021/08/microsoft-graph-why-you-cannot-call-the-me-endpoint-with-a-token-acquired-via-the-client-credentials -授予流/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从中间件请求 MS Graph 访问令牌 - Request a MS Graph Access token from Middleware 如何在没有用户登录的情况下检索 .NET Core Web API 的 MS Graph 访问令牌 - How to retrieve an MS Graph access token for a .NET Core Web API without user sign in Microsoft Graph:我是否可以(重新)使用 AAD 转发的用户 Bearer Token 以便对 Graph API 进行“委托”调用? - Microsoft Graph: Can I (re)use the user's Bearer Token forwarded by AAD in order to make "delegated" calls to the Graph API? 如何在 MS Graph API 中从 Java SDK 获取附件资源的原始内容? - How do I get the raw content of attachment resources from Java SDK in MS Graph API? MS Graph API - 来自 C# 的 getPstnCalls - MS Graph API - getPstnCalls from C# 使用 AAD 用户凭据解析连接字符串时出错 - Error parsing connection string with AAD user credentials 如何使用 Microsoft.Identity.Web 从 AAD 请求 email scope - How to request email scope from AAD using Microsoft.Identity.Web API 不会使用 MSAL 从 SPA 传递的令牌对 AAD 进行身份验证 - API won't authenticate against AAD with token passed from SPA using MSAL java.lang.NoSuchMethodError: 'com.microsoft.aad.msal4j.SilentParameters$SilentParametersBuilder 使用 azure sdk 用于 java 服务总线 - java.lang.NoSuchMethodError: 'com.microsoft.aad.msal4j.SilentParameters$SilentParametersBuilder using azure sdk for java service bus AAD认证后如何重定向到用户导航到的原始路径? - How to redirect to the original path user navigated to after AAD authentication?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM