0
votes

I am trying to connect to Office 365 to use the client credential flow.I have followed all the steps as mentioned in http://blogs.msdn.com/b/exchangedev/archive/2015/01/21/building-demon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow.aspx

I am trying to connect using the ADAL java library.

Using the below code to connect and fetch mail:

String authority = "https://login.windows.net/tenant-id/oauth2/authorize";
ExecutorService service = null;
service=Executors.newFixedThreadPool(1);
try {
    AuthenticationContext authenticationContext =  new AuthenticationContext(authority, false, service);
    String certfile = "PfxFinal.pfx";
    InputStream pkcs12Certificate=new FileInputStream(certfile);

    String token = "";

    AsymmetricKeyCredential credential = AsymmetricKeyCredential.create("clientid", pkcs12Certificate,"password");
    System.out.println("X509 is fine!");

    Future<AuthenticationResult> future=authenticationContext.acquireToken("https://outlook.office365.com", (AsymmetricKeyCredential)credential, null);// authenticationContext.acquireToken("https://outlook.office365.com", credential, null);
    System.out.println("Token Received "+future.get().getAccessToken());
    token=future.get().getAccessToken();
    System.out.println(token);


    URL url = new URL("https://outlook.office365.com/api/v1.0/me/folders/inbox/messages?$count=true&$filter=isread%20eq%20false");
    HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
    con.setRequestMethod("GET"); 
    con.setRequestProperty("Accept","application/json"); 
    //con.setRequestProperty("Authorization",token);
    con.setRequestProperty("Authorization","Bearer "+token);
    System.out.println("Bearer "+token);

    if (con.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + con.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (con.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    con.disconnect();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I have given the full permission for the tenant.Is there anything else , that I have to do in order to fix this issue.

3

3 Answers

0
votes

What Exchange Online permissions did you configure when you registered the application in Azure AD? You should have either Read mail in all mailboxes or Read and write mail in all mailboxes.

0
votes

You are addressing the "/me" endpoint, which for "app-only" access has really no meaning as "me" represents a mailbox and the access token has no user context that could be used to determine what "me" mailbox is attempted to access. For app-only access token you must use users('the mailbox e-mail address to access'). "app-only" represents an application identity with no information about mailboxes or users.

Let me know if you still have issues.

Thanks, Matthias

0
votes

This is resolved and below is a full working code:

public class AccessToken { public static void main(String[] args) {

String authority = "https://login.windows.net/xxxxxxxxxxxxx/oauth2/authorize";
ExecutorService service = null;
service=Executors.newFixedThreadPool(1);
try {
    AuthenticationContext authenticationContext =  new AuthenticationContext(authority, false, service);
    String certfile = "pfx.pfx";
    InputStream pkcs12Certificate=new FileInputStream(certfile);

    String token = "";


    AsymmetricKeyCredential credential = AsymmetricKeyCredential.create("id", pkcs12Certificate,"password");
    System.out.println("X509 is fine!");

    Future<AuthenticationResult> future=authenticationContext.acquireToken("https://outlook.office365.com", (AsymmetricKeyCredential)credential, null);

    token=future.get().getAccessToken();

    Long uuid = UUID.randomUUID().getMostSignificantBits();


    URL url = new URL("https://outlook.office365.com/api/v1.0/users/email/folders/inbox/messages");
    HttpURLConnection con = (HttpURLConnection) url.openConnection(); 

    con.setRequestMethod("GET"); 
    con.setRequestProperty("Accept","application/json"); 
    con.setRequestProperty("User-Agent","Testing/1.0 abc/1.1");
    Date date = new Date();

    SimpleDateFormat ft = 
              new SimpleDateFormat ("E, dd MM yyyy hh:mm:ss zzz");

              System.out.println("Current Date: " + ft.format(date));
              String dateString = ft.format(date);



    con.setRequestProperty("Authorization","Bearer "+token);


    if (con.getResponseCode() != 200) {
        System.out.println(con.getHeaderFields());

        throw new RuntimeException("Failed : HTTP error code : "
                + con.getResponseCode());

    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (con.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    con.disconnect();

    service.shutdown();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

} }

I am able to get the json response from office 365. Another way I tested was using the RestClient plugin of Firefox , with the generated Access Token.