在 Java 中获取 Microsoft Graph API 的令牌

Get token for Microsoft Graph API in Java

我想使用 Microsoft Graph API 来管理云端硬盘文件,但我在身份验证方面遇到了一些问题...

我有下面的代码来获得访问我的帐户的权限:

try(InputStream propFile = MicrosoftEngine.class.getClassLoader().getResourceAsStream("microsoft.properties")){
      Properties prop = new Properties();
      prop.load(propFile);

      setGraphClient(GraphServiceClient.builder().authenticationProvider(request -> {
        // Add the access token in the Authorization header
        request.addHeader("Authorization", "Bearer " + prop.getProperty("token"));
      }).buildClient());

      IDriveItemCollectionPage children = graphClient.me().drive().root().children().buildRequest().get();
      setDrive(children);
    }
    catch(IOException e) {
      e.printStackTrace();
    }

但目前,“令牌”的值 属性 来自 Microsoft Graph Explorer :

Example here

一段时间后(可能一个小时),令牌过期,我需要通过 Graph Explorer 发送另一个请求以获得新令牌,并将其 copy/paste 放入我的 Java 代码中。

但这并不方便...我如何才能在 Java 中获取此令牌值?有什么想法吗?

提前感谢您的帮助:)

对于身份验证,您首先需要实施 MSAL 以从 AAD 获取令牌。您可以从 here to implement authentication in Microsoft Graph. You can try this sample 开始为 JAVA.

实施 Microsoft Graph