简体   繁体   English

使用Java中的Office 365 REST API构建后台驻留程序或服务应用程序

[英]Building Daemon or Service Apps with Office 365 REST API in Java

I am trying to build a batch job to access Office 365 Mail API. 我试图建立一个批处理作业以访问Office 365邮件API。 Up on checking the documentation (the concept is very clear), I wasn't able to find a code sample written for Java. 在检查文档 (概念很明确)之前,我找不到用于Java编写的代码示例。 I've found this but it relies on the java pom file but I would love to use REST API or Graphi API directly if possible. 我已经找到了,但是它依赖于java pom文件,但是如果可能的话,我想直接使用REST API或Graphi API。

Can someone point me on how to get started with building a Daemon service to access Office 365 REST API without users login ? 有人可以指出我如何开始构建后台驻留程序服务以在无需用户登录的情况下访问Office 365 REST API吗?

UPDATE UPDATE

I've the following code to get the token using AADL library 我有以下代码使用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();
        }


    }

Here the Unauthorized error from the http.execute method 这是来自http.execute方法的未经授权的错误

HttpResponseProxy{HTTP/1.1 401 Unauthorized [Content-Type: application/json; HttpResponseProxy {HTTP / 1.1 401未经授权[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,服务器:Microsoft-IIS / 8.5,请求ID:49ca360f-ab4b-42d5-a4b0-9676e4244c21,客户端请求ID:49ca360f-ab4b-42d5-a4b0-9676e4244c21,x-ms-ags-诊断:{“ ServerInfo”:{“ DataCenter”:“美国西部”,“ Slice”:“ SliceA”,“ ScaleUnit”:“ 003”,“主机”:“ 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]}} charset = utf-8,Content-Length:244,Chunked:false]}}

eyJ0eXAiOiJKV1QiLCJxcy76FRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyIsImtpZCI6IlliUkFRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyJ9..BKt54345DIfv2WWT4pQ--Nuy-0aHkkht4332r7E4d5mP-EAEKmcQe7y0IPjkYGZTNhyNiG2tVAyb56Gcbessdsfewz_BNoAolTVukxttXc-pFY1_Ol5Adc8T5yio43ixfs88mrVRqZEHsb7c-wjO-otBXocZs8waYXdree83g1JtcnULs7bAGp3VBUhMjuJ2u87363Yq3lfse39_Pt6tRw] eyJ0eXAiOiJKV1QiLCJxcy76FRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyIsImtpZCI6IlliUkFRUlljRV9tb3RXVkpLSHJ3TEJiZF85cyJ9..BKt54345DIfv2WWT4pQ - Nuy-0aHkkht4332r7E4d5mP-EAEKmcQe7y0IPjkYGZTNhyNiG2tVAyb56Gcbessdsfewz_BNoAolTVukxttXc-pFY1_Ol5Adc8T5yio43ixfs88mrVRqZEHsb7c-WJO-otBXocZs8waYXdree83g1JtcnULs7bAGp3VBUhMjuJ2u87363Yq3lfse39_Pt6tRw]

(the token is something similar to this, just changed it to something similar for security) (令牌与此类似,只是出于安全性考虑将其更改为相似的东西)

Java walkthrough here (though for a web app using auth code flow): https://dev.outlook.com/restapi/tutorial/java 此处的Java演练(尽管对于使用身份验证代码流的Web应用程序而言): https : //dev.outlook.com/restapi/tutorial/java

There's also this sample that uses client credential flow: 还有一个使用客户端凭证流的示例:

https://github.com/jasonjoh/java-calendar-demo https://github.com/jasonjoh/java-calendar-demo

To authenticate in the daemon or service apps, we can use Client Credentials flow. 要在守护程序或服务应用程序中进行身份验证,我们可以使用客户端凭据流。 After we register the app, we would get the secret . 注册该应用程序后,我们将获得秘密 Then we can use the request below direct to get the 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

And to use the Office 365 access token, we can replace the resource with https://outlook.office.com . 要使用Office 365访问令牌,我们可以将资源替换为https://outlook.office.com Here is a detail document about calling Microsoft Graph in a service or daemon app. 是有关在服务或守护程序应用程序中调用Microsoft Graph的详细文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM