使用Java访问受azure active directory保护的web服务

使用Java访问受azure active directory保护的web服务,java,web-services,azure-active-directory,Java,Web Services,Azure Active Directory,背景如下: 使用Tomcat和Springboot的应用程序服务A提供web服务端点。e、 g.https://xxx.azurewebsites.net/appA/order/1111 webapp A受AAD身份验证(快速配置)保护。应用程序(web应用程序)已在AAD中注册。web应用的客户端id为[客户端id] 客户端密码[客户端密码]在web app中创建 AAD目录id为[租户id] 使用浏览器打开上面的URL。显示AD登录页面,输入凭据后,我可以获得预期的json文件 现在我有

背景如下:

  • 使用Tomcat和Springboot的应用程序服务A提供web服务端点。e、 g.
    https://xxx.azurewebsites.net/appA/order/1111
  • webapp A受AAD身份验证(快速配置)保护。应用程序(web应用程序)已在AAD中注册。web应用的客户端id为[客户端id]
  • 客户端密码[客户端密码]在web app中创建
  • AAD目录id为[租户id]
  • 使用浏览器打开上面的URL。显示AD登录页面,输入凭据后,我可以获得预期的json文件
现在我有了另一个控制台应用程序,它尝试从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();
...
字符串权限=”https://login.microsoftonline.com/“+[租户id];
字符串顺序\u URL=”https://xxx.azurewebsites.net/appA/order/1111"
ExecutorService=Executors.newFixedThreadPool(1);
ClientCredential credentials=新的ClientCredential([client id],[client secret]);
AuthenticationContext=新的AuthenticationContext(AUTHORITY、false、service);
Future=context.acquireToken(“https://graph.microsoft.com“,凭据,空);
AuthenticationResult=future.get();
字符串标记=result.getAccessToken();
System.out.println(令牌);
HttpURLConnection conn=(HttpURLConnection)新URL(orderurl).openConnection();
连接设置输出(真);
conn.setRequestProperty(“内容类型”,“应用程序/json;字符集=UTF-8”);
conn.setRequestMethod(“GET”);
conn.setRequestProperty(“授权”、“持有人”+令牌);
连接();
int responseCode=conn.getResponseCode();
系统输出打印LN(响应代码);
InputStream is=conn.getInputStream();
...
我可以获取令牌,但响应代码为401,错误消息是“您没有查看此目录或页面的权限”


那么,我是否需要分配其他API权限才能使其正常工作?或者缺少一些其他设置

我可以重现您的问题,
资源
应该是您要访问的应用程序的
客户端id
应用程序id URI
,而不是MS图形
https://graph.microsoft.com


有些功能需要服务帐户服务主体。因此,请使用使用服务帐户创建的客户端id和客户端密码尝试一次。尝试更改
https://graph.microsoft.com
到要访问的应用程序的
客户端id
应用程序id URI
。是的,Joy是正确的。您没有调用图形API。您需要为您的API获取一个令牌。是的,很高兴,使用
客户端id
现在就可以了,谢谢。我没有设置任何公开API,因此稍后将测试
应用程序ID URI
。不管怎样,我的问题解决了。