Skip to content
This repository has been archived by the owner on Jul 5, 2023. It is now read-only.

ADAL4J Basics

Santiago Gonzalez edited this page Apr 5, 2019 · 7 revisions

ADAL4J(com.microsoft.azure.adal4j) enables developers of applications running on the Java virtual machine to acquire tokens in order to call secured Web APIs. These Web APIs can be the Microsoft Graph, or 3rd party Web APIs.

ADAL4J supports multiple application architectures

  • Native clients (mobile/desktop applications) authentication and calling a Web API in the name of the user. Acquiring tokens for native clients falls under public client flows which do not have an application secret since they cannot be stored securely on native clients.
  • Web clients (Web Apps/Web APIs/Daemons) authentication and calling a Web API in the name of a user, or without a user. Acquiring tokens for web clients and services falls under the confidential client flows which require application credentials.

Before using ADAL4J, you will need to register your application on the Azure Portal.

Installation

You can install ADAL4J either with Maven or Gradle.

Maven

Add the below dependency to your pom.xml file.

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>adal4j</artifactId>
    <version>1.6.3</version>
</dependency>

Gradle

Add the following dependency to your build.gradle file.

compile group: 'com.microsoft.azure', name: 'adal4j', version: '1.6.3'

Usage

Here are the steps to get started with ADAL4J:

  1. Instantiate the ADAL AuthenticationContext object.

    String authority = "https://login.microsoftonline.com/contoso.onmicrosoft.com/";
    ExecutorService service = Executors.newFixedThreadPool(1);
    
    AuthenticationContext context = new AuthenticationContext(authority, true, service);
  2. Use the authentication context instance to acquire tokens. ADAL4J provides different methods to acquire tokens based on your application type. Refer the acquire tokens section for the appropriate method for your implementation.

  3. Use the acquired token as a bearer token in the call to the web API.

    Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(code, redirectUri, new ClientCredential(clientId, clientSecret), null, null);
    AuthenticationResult result = future.get();
    
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Authorization", "Bearer " + result.getAccessToken());

You can also refer this full sample of a web app using ADAL4J to authenticate users and get tokens for the MS Graph API.