使用 Java 访问受 Azure 活动目录保护的 Web 服务

access a azure active directory protected web service using Java

这是背景:

现在我有另一个控制台应用程序试图从 webapp A 获取订单信息。代码如下:

String AUTHORITY = "https://login.microsoftonline.com/" + [tenant-id];
String ORDER_URL = "https://xxx.azurewebsites.net/appA/order/1111"

ExecutorService service = Executors.newFixedThreadPool(1);
ClientCredential credentials = new ClientCredential([client-id], [client-secret]);

AuthenticationContext context = new AuthenticationContext(AUTHORITY, false, service);

Future<AuthenticationResult> future = context.acquireToken("https://graph.microsoft.com", credentials, null);
AuthenticationResult result = future.get();

String token = result.getAccessToken();
System.out.println(token);

HttpURLConnection conn = (HttpURLConnection) new URL(ORDER_URL).openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + token);
conn.connect();

int responseCode = conn.getResponseCode();
System.out.println(responseCode);

InputStream is = conn.getInputStream();
...

我可以获取令牌,但响应代码为 401,错误消息为 "You do not have permission to view this directory or page"。

那么我是否需要分配其他 API 权限才能使其正常工作?或者还有其他一些设置被遗漏了。

我可以重现您的问题,resource 应该是您要访问的应用程序的 client-idApplication ID URI,而不是 MS 图 https://graph.microsoft.com