2017-09-27 153 views
2

我通过Microsoft Graph API访问我的Office 365帐户时遇到问题(或两个问题)。通过图形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; 
    } 
+0

您如何验证用户以获取您传入'/ users'的令牌? –

+0

已更新,代码示例。如果我调用https://graph.microsoft.com/v1.0/me/,则返回代表我的用户的json字符串。但如果我打电话给/ users /我得到了403.我也可以访问sharepoint终点ok并获取网站数据等。 – Gary

+0

User.ReadBasic.All需要管理员同意,你有没有试过做管理员同意?你在哪里注册的应用程序,在天蓝色的门户? –

回答

1

的应用寄存器apps.dev.microsoft.com与工作方法v2.0端点。请点击此处查看有关v2.0端点的更多详情。

您可以使用v2.0 authentication protocolsAzure Active Directory v2.0 authentication libraries获取令牌。在认证期间,您需要为User.ReadBasic.All权限执行用户同意或管理员同意。同意后,访问令牌包含该委托权限,并在调用列表用户操作时起作用。

+0

不幸的是,我使用的是v2.0端点和库,但它似乎是应用程序的问题。注册门户。 – Gary

1

好吧,我想我应该张贴答案。首先,也是最容易混淆的一点,apps.dev.microsoft.com注册似乎不起作用(即使我使用的是V2.0端点和版本2库)。

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

看起来很奇怪,尽管认证/授权服务对我的应用程序是标准的,并且完美地用于访问Sharepoint/One Drive等,但是当想要击中用户端点时,它只会在注册时才起作用portal.azure.com。

非常感谢大家的帮助。