Edit

Share via


Build Java apps with Microsoft Graph

This tutorial teaches you how to build a Java console app that uses the Microsoft Graph API to access data on behalf of a user.

Note

To learn how to use Microsoft Graph to access data using app-only authentication, see this app-only authentication tutorial.

In this tutorial, you will:

Tip

As an alternative to following this tutorial, you can download the completed code through the quick start tool, which automates app registration and configuration. The downloaded code works without any modifications required.

You can also download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.

Prerequisites

Before you start this tutorial, you should have the Java SE Development Kit (JDK) and Gradle installed on your development machine.

You should also have a Microsoft work or school account with an Exchange Online mailbox. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a one-month free trial or purchase a Microsoft 365 plan.

Note

This tutorial was written with OpenJDK version 17.0.2 and Gradle 7.4.2. The steps in this guide might work with other versions, but that hasn't been tested.

Register an application for user authentication

Register an application that supports user authentication using device code flow. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.

  1. Open a browser and navigate to the Microsoft Entra admin center and sign in using a Global administrator account.

  2. Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.

    A screenshot of the App registrations

  3. Select New registration. Enter a name for your application, for example, Graph User Auth Tutorial.

  4. Set Supported account types as desired. The options are:

    Option Who can sign in?
    Accounts in this organizational directory only Only users in your Microsoft 365 organization
    Accounts in any organizational directory Users in any Microsoft 365 organization (work or school accounts)
    Accounts in any organizational directory ... and personal Microsoft accounts Users in any Microsoft 365 organization (work or school accounts) and personal Microsoft accounts
  5. Leave Redirect URI empty.

  6. Select Register. On the application's Overview page, copy the value of the Application (client) ID and save it. You'll need it in the next step. If you chose Accounts in this organizational directory only for Supported account types, also copy the Directory (tenant) ID and save it.

    A screenshot of the application ID of the new app registration

  7. Select Authentication under Manage. Locate the Advanced settings section and change the Allow public client flows toggle to Yes, then choose Save.

    A screenshot of the Allow public client flows toggle

Note

Notice that you didn't configure any Microsoft Graph permissions on the app registration. The sample uses dynamic consent to request specific permissions for user authentication.

Create a Java console app

Create a basic Java console app.

  1. Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command to create a new Gradle project.

    gradle init --dsl groovy --test-framework junit --type java-application --project-name graphtutorial --package graphtutorial
    
  2. Once the project is created, verify that it works by running the following command to run the app in your CLI.

    ./gradlew --console plain run
    

    If it works, the app should output Hello World..

Install dependencies

Before moving on, add dependencies that you use later.

  1. Open ./app/build.gradle. Update the dependencies section to add those dependencies.

    dependencies {
        // Use JUnit test framework.
        testImplementation 'junit:junit:4.13.2'
    
        // This dependency is used by the application.
        implementation 'com.google.guava:guava:33.4.6-jre'
        implementation 'com.azure:azure-identity:1.15.4'
        implementation 'com.microsoft.graph:microsoft-graph:6.33.0'
    }
    
  2. Add the following to the end of ./app/build.gradle.

    run {
        standardInput = System.in
    }
    

    The next time you build the project, Gradle will download those dependencies.

Load application settings

Next, add the details of your app registration to the project.

  1. Create a new directory named graphtutorial in the ./app/src/main/resources directory.

  2. Create a new file in the ./app/src/main/resources/graphtutorial directory named oAuth.properties, and add the following text in that file.

    app.clientId=YOUR_CLIENT_ID_HERE
    app.tenantId=common
    app.graphUserScopes=user.read,mail.read,mail.send
    
  3. Update the values according to the following table.

    Setting Value
    app.clientId The client ID of your app registration
    app.tenantId If you chose the option to only allow users in your organization to sign in, change this value to your tenant ID. Otherwise leave as common.

    Important

    If you're using source control such as git, now would be a good time to exclude the oAuth.properties file from source control to avoid inadvertently leaking your app ID.

Design the app

Continue by creating a simple console-based menu.

  1. Open ./app/src/main/java/graphtutorial/App.java and add the following import statements.

    package graphtutorial;
    
    import java.io.IOException;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.time.format.FormatStyle;
    import java.util.InputMismatchException;
    import java.util.Properties;
    import java.util.Scanner;
    
    import com.microsoft.graph.models.Message;
    import com.microsoft.graph.models.MessageCollectionResponse;
    import com.microsoft.graph.models.User;
    
  2. Replace the existing main function with the following.

    public static void main(String[] args) {
        System.out.println("Java Graph Tutorial");
        System.out.println();
    
        final Properties oAuthProperties = new Properties();
        try {
            oAuthProperties.load(App.class.getResourceAsStream("oAuth.properties"));
        } catch (IOException e) {
            System.out.println("Unable to read OAuth configuration. Make sure you have a properly formatted oAuth.properties file. See README for details.");
            return;
        }
    
        initializeGraph(oAuthProperties);
    
        greetUser();
    
        Scanner input = new Scanner(System.in);
    
        int choice = -1;
    
        while (choice != 0) {
            System.out.println("Please choose one of the following options:");
            System.out.println("0. Exit");
            System.out.println("1. Display access token");
            System.out.println("2. List my inbox");
            System.out.println("3. Send mail");
            System.out.println("4. Make a Graph call");
    
            try {
                choice = input.nextInt();
            } catch (InputMismatchException ex) {
                // Skip over non-integer input
            }
    
            input.nextLine();
    
            // Process user choice
            switch(choice) {
                case 0:
                    // Exit the program
                    System.out.println("Goodbye...");
                    break;
                case 1:
                    // Display access token
                    displayAccessToken();
                    break;
                case 2:
                    // List emails from user's inbox
                    listInbox();
                    break;
                case 3:
                    // Send an email message
                    sendMail();
                    break;
                case 4:
                    // Run any Graph code
                    makeGraphCall();
                    break;
                default:
                    System.out.println("Invalid choice");
            }
        }
    
        input.close();
    }
    
  3. Add the following placeholder methods at the end of the file. You implement them in later steps.

    private static void initializeGraph(Properties properties) {
        // TODO
    }
    
    private static void greetUser() {
        // TODO
    }
    
    private static void displayAccessToken() {
        // TODO
    }
    
    private static void listInbox() {
        // TODO
    }
    
    private static void sendMail() {
        // TODO
    }
    
    private static void makeGraphCall() {
        // TODO
    }
    

This implements a basic menu and reads the user's choice from the command line.

  1. Delete ./app/src/test/java/graphtutorial/AppTest.java.

Next step