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 abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.
- Authentication (Kiota default Azure authentication)
- HTTP (Kiota default OkHttp-based implementation)
- Form serialization (Kiota default)
- JSON serialization (Kiota default)
- Text serialization (Kiota default)
- Multipart serialization (Kiota default)
- Jakarta annotations Maven Central
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-abstractions:1.3.0'
implementation 'com.microsoft.kiota:microsoft-kiota-authentication-azure:1.3.0'
implementation 'com.microsoft.kiota:microsoft-kiota-http-okHttp:1.3.0'
implementation 'com.microsoft.kiota:microsoft-kiota-serialization-json:1.3.0'
implementation 'com.microsoft.kiota:microsoft-kiota-serialization-text:1.3.0'
implementation 'com.microsoft.kiota:microsoft-kiota-serialization-form:1.3.0'
implementation 'com.microsoft.kiota:microsoft-kiota-serialization-multipart:1.3.0'
implementation 'com.azure:azure-identity:1.13.2'
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
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.
Open a browser and navigate to the Azure Active Directory admin center. Sign in with your Azure account.
Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.
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.
- Set Name to
Select Register. On the Overview page, copy the value of the Application (client) ID and save it.
Select Authentication under Manage.
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.http.OkHttpRequestAdapter;
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 OkHttpRequestAdapter adapter = new OkHttpRequestAdapter(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
- kiota-samples repository contains the code from this guide.
- ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and sample clients in multiple languages.