如何在创建 Microsoft Graph 客户端后获取邮箱 (JAVA - Eclipse IDE)?

How to get Mailbox after creating a Microsoft Graph Client (JAVA - Eclipse IDE)?

我已经使用 Azure AD 和 JAVA 成功创建了一个 MS Graph 客户端。我已经使用 ClientSecretCredential 进行身份验证。我相信收到的访问令牌也是有效的。但是,我现在想使用 MS Graph 和 JAVA 访问我的(outlook)邮箱,以计算收件箱文件夹中的电子邮件总数。请在下面找到我的代码和错误。我认为这是因为代码是针对委托而不是应用程序权限的。请帮忙。

package JAVA_MicrosoftGraphAPI;

import java.net.URL;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.PropertyConfigurator;

import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.logger.DefaultLogger;
import com.microsoft.graph.logger.LoggerLevel;
import com.microsoft.graph.options.Option;
import com.microsoft.graph.options.QueryOption;
import com.microsoft.graph.requests.GraphServiceClient;
import com.microsoft.graph.requests.MessageCollectionPage;

public class soTest {

    // for requirements visit:
    // https://github.com/Azure/azure-sdk-for-java/wiki/Set-up-Your-Environment-for-Authentication#enable-applications-for-device-code-flow
    private final static String CLIENT_ID = "XXXXXXXXXXXXX";
    private final static String TENANT_ID = "XXXXXXXXXXXXX";
    private final static String SECRET_Value = "XXXXXXXXXXXXX";

    // Set the scopes for your ms-graph request
    private final static List<String> SCOPES = Arrays.asList("https://graph.microsoft.com/.default");

    public static void main(String[] args) throws Exception {


        final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                .clientId(CLIENT_ID)
                .clientSecret(SECRET_Value)
                .tenantId(TENANT_ID)
                .build();


        final TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(SCOPES, clientSecretCredential);
        System.out.println("First Step Reached. ");


        // Create default logger to only log errors
        DefaultLogger logger = new DefaultLogger();
        logger.setLoggingLevel(LoggerLevel.ERROR);


        // Build a Graph client
        GraphServiceClient graphClient = GraphServiceClient.builder()
                .authenticationProvider(tokenCredAuthProvider)
                .logger(logger)
                .buildClient();
        System.out.println("Second Step Reached. ");


        //      final OkHttpClient httpClient = HttpClients.createDefault(tokenCredAuthProvider);
        //      final Request request = new Request.Builder().url("https://graph.microsoft.com/v1.0/me").build();
        // Redirecting to web browser and signing in for authentication and connection.
        URL myUrl = new URL("https://graph.microsoft.com/v1.0/me/");
        final String accessToken = tokenCredAuthProvider.getAuthorizationTokenAsync(myUrl).get();
        System.out.println("Access token --> " + accessToken);


        LinkedList<Option> requestOptions = new LinkedList<Option>();
        requestOptions.add(new QueryOption("/select", "internetMessageHeaders"));

        MessageCollectionPage messages = graphClient.me().messages()
            .buildRequest( requestOptions )
            .get();
    
    }

}


Exception in thread "main" com.microsoft.graph.http.GraphServiceException: Error code: BadRequest
Error message: /me request is only valid with delegated authentication flow.

GET https://graph.microsoft.com/v1.0/me/messages?%2Fselect=internetMessageHeaders
SdkVersion : graph-java/v5.14.0


400 : Bad Request
[...]

[Some information was truncated for brevity, enable debug logging for more details]
    at com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:419)
    at com.microsoft.graph.http.GraphServiceException.createFromResponse(GraphServiceException.java:378)
    at com.microsoft.graph.http.CoreHttpProvider.handleErrorResponse(CoreHttpProvider.java:514)
    at com.microsoft.graph.http.CoreHttpProvider.processResponse(CoreHttpProvider.java:443)
    at com.microsoft.graph.http.CoreHttpProvider.sendRequestInternal(CoreHttpProvider.java:409)
    at com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:226)
    at com.microsoft.graph.http.CoreHttpProvider.send(CoreHttpProvider.java:203)
    at com.microsoft.graph.http.BaseCollectionRequest.send(BaseCollectionRequest.java:103)
    at com.microsoft.graph.http.BaseEntityCollectionRequest.get(BaseEntityCollectionRequest.java:78)
    at JAVA_MicrosoftGraphAPI.soTest.main(soTest.java:75)

您似乎正在使用客户端凭据流。这意味着令牌将在应用程序的上下文中具有应用程序声明,即 运行。因此你不能在这里使用 /me 端点。

您可以改用 users/id。 或者,您可以使用 OAuth 授权代码流(令牌将同时具有用户和应用程序声明)来利用 /me 端点。

按照教程 here 相应地生成访问令牌。