通过Graph API访问Office 365

时间:2017-09-27 13:37:50

标签: azure-active-directory microsoft-graph

关于通过Microsoft Graph API访问我的Office 365帐户,我遇到了一两个问题。

第一个问题是我有一个java程序试图列出office 365订阅中的所有用户。我打电话给https://graph.microsoft.com/v1.0/users/,但回到了403 forbidden

在应用注册时,我已在委派和应用权限上添加了User.ReadUser.ReadBasic.AllUser.ReadWrite权限。

我还尝试使用Graph Explorer,但当我输入使用我的帐户时,它仍然使用内置图形用户,并且不显示我的应用程序登录信息。不确定这些是否相关。

以下是导致403

的代码段
AuthenticationResult result = getAccessTokenFromUserCredentials(RESOURCE_GRAPH, ID, PASSWORD);

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

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer "+result.getAccessToken());
if (conn.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + conn.getResponseCode());
}

这是获取令牌的方法

private static AuthenticationResult getAccessTokenFromUserCredentials(String resource,
                                                                          String username, String password) throws Exception {
        AuthenticationContext context;
        AuthenticationResult result = null;
        ExecutorService service = null;
        try {
            service = Executors.newFixedThreadPool(1);
            context = new AuthenticationContext(AUTHORITY, false, service);
            Future<AuthenticationResult> future = context.acquireToken(
                    resource, CLIENT_ID, username, password,
                    null);
            result = future.get();
        } finally {
            service.shutdown();
        }

        if (result == null) {
            throw new ServiceUnavailableException(
                    "authentication result was null");
        }
        return result;
    }

2 个答案:

答案 0 :(得分:1)

apps.dev.microsoft.com中的app注册与v2.0端点一起使用。请点击此处了解有关v2.0端点的更多详细信息。

您可以使用v2.0 authentication protocolsAzure Active Directory v2.0 authentication libraries获取令牌。在身份验证期间,您需要获得User.ReadBasic.All权限的用户许可或管理员同意。在同意之后,访问令牌包括该委托权限,并且在调用列表用户操作时将起作用。

答案 1 :(得分:1)

好的,以为我应该发布答案。首先,最令人困惑的是,apps.dev.microsoft.com注册似乎不起作用(即使我使用的是V2.0端点和版本2库)。

但是,当我直接使用azure门户注册应用程序时,这解决了问题。我随后能够正确访问该服务。

虽然身份验证/授权服务是我的应用程序的标准服务并且非常适合访问Sharepoint / One Drive等,但是,当想要访问用户端点时,它只会在注册到用户端点时工作,这似乎很奇怪。 portal.azure.com。

非常感谢大家的帮助。