Build API clients for Java with Microsoft identity authentication

Required tools

Create a project

Use Gradle to initialize a Java application project.

gradle init --dsl groovy --test-framework junit --type java-application --project-name getuserclient --package getuserclient

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the bundle package. For more information about kiota dependencies, refer to the dependencies documentation.

For this tutorial, use the default implementations.

Edit ./app/build.gradle to add the following dependencies.

Note

Find current version numbers for Kiota packages at Nexus Repository Manager.

implementation 'jakarta.annotation:jakarta.annotation-api:3.0.0'
implementation 'com.microsoft.kiota:microsoft-kiota-bundle:1.7.0'
implementation 'com.microsoft.kiota:microsoft-kiota-authentication-azure:1.7.0'
implementation 'com.azure:azure-identity:1.14.0'

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.

openapi: 3.0.3
info:
  title: Microsoft Graph get user API
  version: 1.0.0
servers:
  - url: https://graph.microsoft.com/v1.0/
paths:
  /me:
    get:
      responses:
        200:
          description: Success!
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/microsoft.graph.user"
components:
  schemas:
    microsoft.graph.user:
      type: object
      properties:
        id:
          type: string
        displayName:
          type: string

You can then use the Kiota command line tool to generate the SDK classes.

kiota generate -l java -d get-me.yml -c GetUserApiClient -n getuserclient.apiclient -o ./app/src/main/java/getuserclient/apiclient --ds none -s none

Register an application

To be able to authenticate with the Microsoft identity platform and get an access token for Microsoft Graph, you need to create an application registration. You can install the Microsoft Graph PowerShell SDK and use it to create the app registration, or register the app manually in the Azure Active Directory admin center.

The following instructions register an app and enable device code flow for authentication.

  1. Open a browser and navigate to the Azure Active Directory admin center. Sign in with your Azure account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Kiota Test Client.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Leave Redirect URI blank.
  4. Select Register. On the Overview page, copy the value of the Application (client) ID and save it.

  5. Select Authentication under Manage.

  6. Locate the Advanced settings section. Set the Allow public client flows toggle to Yes, then select Save.

Create the client application

The final step is to update the ./app/src/main/java/getuserclient/App.java file that was generated as part of the console application to include the following code. Replace YOUR_CLIENT_ID with the client ID from your app registration.

package getuserclient;

import com.azure.identity.DeviceCodeCredential;
import com.azure.identity.DeviceCodeCredentialBuilder;
import com.microsoft.kiota.authentication.AzureIdentityAuthenticationProvider;
import com.microsoft.kiota.bundle.DefaultRequestAdapter;

import getuserclient.apiclient.GetUserApiClient;
import getuserclient.apiclient.models.User;


public class App {

    public static void main(String[] args) {
        final String clientId = "YOUR_CLIENT_ID";

        // The auth provider will only authorize requests to
        // the allowed hosts, in this case Microsoft Graph
        final String[] allowedHosts = new String[] { "graph.microsoft.com" };
        final String[] graphScopes = new String[] { "User.Read" };

        final DeviceCodeCredential credential = new DeviceCodeCredentialBuilder()
            .clientId(clientId)
            .challengeConsumer(challenge -> System.out.println(challenge.getMessage()))
            .build();


        final AzureIdentityAuthenticationProvider authProvider =
            new AzureIdentityAuthenticationProvider(credential, allowedHosts, graphScopes);
        final DefaultRequestAdapter adapter = new DefaultRequestAdapter(authProvider);

        final GetUserApiClient client = new GetUserApiClient(adapter);

        try {
            final User me = client.me().get();
            System.out.printf("Hello %s, your ID is %s%n",
                    me.getDisplayName(), me.getId());
        } catch (Exception err) {
            System.out.printf("Error: %s%n", err.getMessage());
        }
    }
}

Note

This example uses the DeviceCodeCredential class. You can use any of the credential classes from the com.azure.identity library.

Run the application

To start the application, run the following command in your project directory.

./gradlew --console plain run

See also