在 Java 中使用 Office 365 REST API 构建守护程序或服务应用程序
Building Daemon or Service Apps with Office 365 REST API in Java
我正在尝试构建批处理作业以访问 Office 365 邮件 API。检查 documentation (the concept is very clear), I wasn't able to find a code sample written for Java. I've found this 但它依赖于 java pom 文件,但如果可能的话,我想直接使用 REST API 或 Graphi API。
有人可以告诉我如何开始构建守护进程服务以在没有用户登录的情况下访问 Office 365 REST API 吗?
更新
我有以下代码使用 AADL 库获取令牌
String tenant="....";
String authority = "https://login.windows.net/"+tenant+"/oauth2/authorize";
ExecutorService service=null;
service= Executors.newFixedThreadPool(1);
try{
AuthenticationContext authenticationContext= new AuthenticationContext(authority,false,service);
String certFile="/mycert2.pfx";
InputStream pkcs12Cert= new SharedFileInputStream(certFile);
AsymmetricKeyCredential credential=AsymmetricKeyCredential.create("....",pkcs12Cert,"pass");
Future<AuthenticationResult> future=authenticationContext.acquireToken("https://outlook.office365.com",credential,null);
System.out.println("Token Received"+future.get().getAccessToken());
String token = future.get().getAccessToken();
HttpGet httpGet = new HttpGet("https://graph.microsoft.com/v1.0/users");
httpGet.setHeader("Authorization", "Bearer "+token);
GraphServices graphServices = new GraphServices();
ResponseEntity<String> responseEntity;
//responseEntity = graphServices.getEmails(token); //Throws the same Unauthorized exception
HttpClient httpClient= HttpClients.createDefault();
HttpResponse response=httpClient.execute(httpGet);
//response contains Unauthorized access
HttpEntity entity=response.getEntity();
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
}
这里是 http.execute 方法的未授权错误
HttpResponseProxy{HTTP/1.1 401 Unauthorized [Content-Type:
application/json; charset=utf-8, Server: Microsoft-IIS/8.5,
request-id: 49ca360f-ab4b-42d5-a4b0-9676e4244c21, client-request-id:
49ca360f-ab4b-42d5-a4b0-9676e4244c21, x-ms-ags-diagnostic:
{"ServerInfo":{"DataCenter":"West
US","Slice":"SliceA","ScaleUnit":"003","Host":"AGSFE_IN_8","ADSiteName":"WST"}},
X-Powered-By: ASP.NET, Date: Tue, 06 Sep 2016 20:43:24 GMT,
Content-Length: 244] ResponseEntityProxy{[Content-Type:
application/json; charset=utf-8,Content-Length: 244,Chunked: false]}}
eyJ0eXAiOiJKV1QiLCJxcy76FRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyIsImtpZCI6IlliUkFRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyJ9.eyJhdWdfsas32sub2ZmaWNlMzY1LmNvbSIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2YwMjYzMzUzLWFlYjItNGE4YS1iZThhLTc3Mzc3MmE2MGJlMy8iLCJpYXQiOjE0NzMxOTQ4MjIsIm5iZiI6MTQ3MzE5NDgyMiwiZXhwIjoxNDczMTk4NzIyLCJhcHBpZCI6IjhhNjc2ZjJkLWU1M2MtNDViNy05MzhhLTdiOTE1YjVkZTRiNiIsImFwcGlkYWNyIjoiMasdff4577dHMud2luZG93cy5uZXQvZjAyNjMzNTMtYWViMi00YThhLWJlOGEtNzczNzcyYTYwYmUzLyIsIm9pZCI6IjQ3NDhkZDE5LTAxOTUtNDcwOC04MTNkLTQxMTdhNDhlMTdmOCIsInN1YiI6IjQ3NDhkZDE5LTAxOTUtNDcwOC04MTNkLTQxMTdhNDhlMTdmOCIsInRpZCI6ImYwMjYzMzUzLWFlYjItNGE4YS1iZThhLTc3Mzc3MmE2MGJlMyIsInZlciI6IjEuMCJ9.BKt54345DIfv2WWT4pQ--Nuy-0aHkkht4332r7E4d5mP-EAEKmcQe7y0IPjkYGZTNhyNiG2tVAyb56Gcbessdsfewz_BNoAolTVukxttXc-pFY1_Ol5Adc8T5yio43ixfs88mrVRqZEHsb7c-wjO-otBXocZs8waYXdree83g1JtcnULs7bAGp3VBUhMjuJ2u87363Yq3lfse39_Pt6tRw]
(token跟这个差不多,为了安全改成类似的)
要在守护程序或服务应用程序中进行身份验证,我们可以使用 客户端凭据 流程。注册应用程序后,我们将获得 secret。然后我们可以直接使用下面的请求来获取app-only access token:
POST https://login.microsoftonline.com/<tenantId>/oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=<clientId>
&client_secret=<clientSecret>
&resource=https://graph.microsoft.com
要使用 Office 365 访问令牌,我们可以将资源替换为 https://outlook.office.com
。 Here 是有关在服务或守护程序应用程序中调用 Microsoft Graph 的详细文档。
Java 此处演练(尽管对于使用授权代码流的 Web 应用程序):https://dev.outlook.com/restapi/tutorial/java
还有这个使用客户端凭证流的示例:
我正在尝试构建批处理作业以访问 Office 365 邮件 API。检查 documentation (the concept is very clear), I wasn't able to find a code sample written for Java. I've found this 但它依赖于 java pom 文件,但如果可能的话,我想直接使用 REST API 或 Graphi API。
有人可以告诉我如何开始构建守护进程服务以在没有用户登录的情况下访问 Office 365 REST API 吗?
更新
我有以下代码使用 AADL 库获取令牌
String tenant="....";
String authority = "https://login.windows.net/"+tenant+"/oauth2/authorize";
ExecutorService service=null;
service= Executors.newFixedThreadPool(1);
try{
AuthenticationContext authenticationContext= new AuthenticationContext(authority,false,service);
String certFile="/mycert2.pfx";
InputStream pkcs12Cert= new SharedFileInputStream(certFile);
AsymmetricKeyCredential credential=AsymmetricKeyCredential.create("....",pkcs12Cert,"pass");
Future<AuthenticationResult> future=authenticationContext.acquireToken("https://outlook.office365.com",credential,null);
System.out.println("Token Received"+future.get().getAccessToken());
String token = future.get().getAccessToken();
HttpGet httpGet = new HttpGet("https://graph.microsoft.com/v1.0/users");
httpGet.setHeader("Authorization", "Bearer "+token);
GraphServices graphServices = new GraphServices();
ResponseEntity<String> responseEntity;
//responseEntity = graphServices.getEmails(token); //Throws the same Unauthorized exception
HttpClient httpClient= HttpClients.createDefault();
HttpResponse response=httpClient.execute(httpGet);
//response contains Unauthorized access
HttpEntity entity=response.getEntity();
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
}
这里是 http.execute 方法的未授权错误
HttpResponseProxy{HTTP/1.1 401 Unauthorized [Content-Type: application/json; charset=utf-8, Server: Microsoft-IIS/8.5, request-id: 49ca360f-ab4b-42d5-a4b0-9676e4244c21, client-request-id: 49ca360f-ab4b-42d5-a4b0-9676e4244c21, x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"West US","Slice":"SliceA","ScaleUnit":"003","Host":"AGSFE_IN_8","ADSiteName":"WST"}}, X-Powered-By: ASP.NET, Date: Tue, 06 Sep 2016 20:43:24 GMT, Content-Length: 244] ResponseEntityProxy{[Content-Type: application/json; charset=utf-8,Content-Length: 244,Chunked: false]}}
eyJ0eXAiOiJKV1QiLCJxcy76FRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyIsImtpZCI6IlliUkFRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyJ9.eyJhdWdfsas32sub2ZmaWNlMzY1LmNvbSIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2YwMjYzMzUzLWFlYjItNGE4YS1iZThhLTc3Mzc3MmE2MGJlMy8iLCJpYXQiOjE0NzMxOTQ4MjIsIm5iZiI6MTQ3MzE5NDgyMiwiZXhwIjoxNDczMTk4NzIyLCJhcHBpZCI6IjhhNjc2ZjJkLWU1M2MtNDViNy05MzhhLTdiOTE1YjVkZTRiNiIsImFwcGlkYWNyIjoiMasdff4577dHMud2luZG93cy5uZXQvZjAyNjMzNTMtYWViMi00YThhLWJlOGEtNzczNzcyYTYwYmUzLyIsIm9pZCI6IjQ3NDhkZDE5LTAxOTUtNDcwOC04MTNkLTQxMTdhNDhlMTdmOCIsInN1YiI6IjQ3NDhkZDE5LTAxOTUtNDcwOC04MTNkLTQxMTdhNDhlMTdmOCIsInRpZCI6ImYwMjYzMzUzLWFlYjItNGE4YS1iZThhLTc3Mzc3MmE2MGJlMyIsInZlciI6IjEuMCJ9.BKt54345DIfv2WWT4pQ--Nuy-0aHkkht4332r7E4d5mP-EAEKmcQe7y0IPjkYGZTNhyNiG2tVAyb56Gcbessdsfewz_BNoAolTVukxttXc-pFY1_Ol5Adc8T5yio43ixfs88mrVRqZEHsb7c-wjO-otBXocZs8waYXdree83g1JtcnULs7bAGp3VBUhMjuJ2u87363Yq3lfse39_Pt6tRw]
(token跟这个差不多,为了安全改成类似的)
要在守护程序或服务应用程序中进行身份验证,我们可以使用 客户端凭据 流程。注册应用程序后,我们将获得 secret。然后我们可以直接使用下面的请求来获取app-only access token:
POST https://login.microsoftonline.com/<tenantId>/oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=<clientId>
&client_secret=<clientSecret>
&resource=https://graph.microsoft.com
要使用 Office 365 访问令牌,我们可以将资源替换为 https://outlook.office.com
。 Here 是有关在服务或守护程序应用程序中调用 Microsoft Graph 的详细文档。
Java 此处演练(尽管对于使用授权代码流的 Web 应用程序):https://dev.outlook.com/restapi/tutorial/java
还有这个使用客户端凭证流的示例: