简体   繁体   English

使用java通过microsoft graph访问office 365 planner

[英]Using java to access office 365 planner via microsoft graph

I am trying to get a list of tasks in a ms planner.我正在尝试在 ms planner 中获取任务列表。 I have some code that worked with a redirect, which presented a authentication code to validate the user via the ms java api PublicClientApplication object.我有一些与重定向一起使用的代码,它提供了一个身份验证代码以通过 ms java api PublicClientApplication 对象验证用户。

''' '''

///
///   Already defined after registering an application in azure AD
///    private static String applicationId;
///    private static String tennantId;
///
public String getUserAccessToken(String[] scopes)  {
    try {

        PublicClientApplication app;
        try {
            // Build the MSAL application object with
            // app ID and authority

            String authority = "https://login.microsoftonline.com/";
            app = PublicClientApplication.builder(applicationId)
                    .authority(authority + tennantId + "/")
                    .build();
        } catch (MalformedURLException e) {
            return null;
        }

        // Create consumer to receive the DeviceCode object
        // This method gets executed during the flow and provides
        // the URL the user logs into and the device code to enter
        Consumer<DeviceCode> deviceCodeConsumer = (DeviceCode deviceCode) -> {
            span.log(ImmutableMap.of("event", "o365-initialise-authentication-device-code-check", "", ""));
            // Print the login information to the console
            System.out.println(deviceCode.message());
        };

        // Request a token, passing the requested permission scopes
        IAuthenticationResult result = app.acquireToken(
                DeviceCodeFlowParameters
                        .builder(scopeSet, deviceCodeConsumer)
                        .build()
        ).exceptionally(ex -> {
            return null;
        }).join();

        if (result != null) {
            return result.accessToken();
        }
    return null;
}

public void getPlan(string planId)
{

            // Build a Graph client
            graphClient = GraphServiceClient.builder()
                    .authenticationProvider((IAuthenticationProvider) authProvider)
                    .logger(logger)
                    .buildClient();

    PlannerBucketCollectionPage existingBuckets = graphClient.planner().plans(planId).buckets().buildRequest().get();
}

''' '''

This works with existingBuckets call returning the buckets in the plan defined by planId这适用于返回 planId 定义的计划中的存储桶的 existingBuckets 调用

I now wish to automate the code via a daemon that doesn't require user access and the authentication code is now: ''' public String getUserAccessToken(String[] scopes) {我现在希望通过不需要用户访问的守护进程自动执行代码,并且身份验证代码现在是:''' public String getUserAccessToken(String[] scopes) {

    try {

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

        ConfidentialClientApplication app = ConfidentialClientApplication.builder(
                applicationId,
                ClientCredentialFactory.create(key))
                .authority(authority + tennantId + "/")
                .build();

        ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                Collections.singleton(GRAPH_DEFAULT_SCOPE))
                .build();

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

        BiConsumer<IAuthenticationResult, Throwable> processAuthResult = (res, ex) -> {
            if (ex != null) {
                System.out.println("Oops! We have an exception - " + ex.getMessage());
            }
            else
            {
                System.out.println("Returned ok - " + res);
                System.out.println("Access Token - " + res.accessToken());
                System.out.println("ID Token - " + res.idToken());
            }
        };

        future.whenCompleteAsync(processAuthResult);
        future.join();

        CompletableFuture<Set<IAccount>> accountsRequest = app.getAccounts();
        BiConsumer<Set<IAccount>, Throwable> processAccountsResult = (res, ex) -> {
            if (ex != null) {
                System.out.println("Oops! We have an exception - " + ex.getMessage());
            }

            if ( res == null )
            {
                System.out.println("No accounts");
            }
            else
            {
                log.info("Found "+ res.size() + " accounts");
            }
        };

        accountsRequest.whenCompleteAsync(processAccountsResult);

        CompletableFuture<IAuthenticationResult> future1;
        try {
            future1 = app.acquireTokenSilently
                    (SilentParameters.builder(Collections.singleton(GRAPH_DEFAULT_SCOPE),
                            null)
                            .forceRefresh(true)
                            .build());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

        future1.join();
        IAccount account = app.getAccounts().join().iterator().next();
        app.removeAccount(account).join();

        return future.get().accessToken();
    }
    catch ( Exception ex)
    {
        log.error("Unable to get O365 token", ex);
    }
    return null;
}

''' '''

However, the account objects are null, and if I skip the future1 call, then I get an http error 401.但是,帐户对象为空,如果我跳过 future1 调用,则会收到 http 错误 401。

Any help / guidance gratefully received.感谢您收到任何帮助/指导。

Thanks in advance提前致谢

Access to planner by using client credentials(without user access) is currently not supported.当前不支持使用客户端凭据(无用户访问权限)访问规划器。

You can vote it up on Microsoft Forums( Microsoft graph feature requests ).您可以在 Microsoft 论坛( Microsoft 图形功能请求)上对其进行投票。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM