In order to use the Azure Resource Manager REST APIs, the HTTP requests need to include the proper authentication header. In order to generate the authentication header, you need to authenticate either an Organizational Account or a Service Principal against the Active Directory in Azure Account. In addition, you will need to create an Application with permissions to access the Service Management API, if you are using the Organizational Account.

If you are not familiar with any of the above, you can explore the following links:

  • For creating an Organizational Account in Azure, the basics using the CLI are covered here.
  • Service Principals are covered here.
  • Giving an Application permission to the Service Management API is covered here.

If you are going to authenticate an Organizational Account, you will need:

  • Account username
  • Account password
  • Client ID of the of the Application granted permissions to the Service Management API.

For authenticating as a Service Principal, the Service Principal is already associated with a particular user account. So you will need:

  • Client ID of the Service Principal
  • Password assigned to the Service Principal

In addition, for developing the Java code, you will need the Microsoft Azure Active Directory Authentication Library (ADAL) for Java. In the source code for the library, there are examples. This tutorial will use that library.

There are two URLs necessary for authenticating. The first is for authenticating the user (and retrieving a credential). The second is the URL one is asking permissions to perform actions on. Since we are targeting the new Azure Resource Manager APIs, as opposed to the older management API, the URLs are:

Additionally, you will need one piece of information specific to the Active Directory one is authenticating against — the tenant id. To find the tenant id, consult this MSDN post.

So, once you’ve set up the ADAL library into your project, you will need to include the following headers:

import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential; // for service principal

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

Next, for authenticating an Organizational Account, you have username, password, and the client id. That block of code to retrieve a credential is as follows:

// Account specific values
String tenantId = <your tenant id>
String username = <your username>
String password = <your password>
String clientId = <your client id>

// use adal to Authenticate
AuthenticationContext authContext = null;
AuthenticationResult authResult = null;
ExecutorService service = null;

try {
    service = Executors.newFixedThreadPool(1);
    String url = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
    authContext = new AuthenticationContext(url,
                                            false,
                                            service);
    Future<AuthenticationResult> future = authContext.acquireToken("https://management.azure.com/",
                                                               clientId,
                                                               username,
                                                               password,
                                                               null);
    authResult = future.get();
} catch (Exception ex) {
    // handle exception as needed
} finally {
    service.shutdown();
}

In the case where you are authenticating using a Service Principal, you have client id and password. The block of code to retrieve the credential in this case is very similar to the above with a different call to the acquireToken method.

// Account specific values
String tenantId = <your tenant id>
String clientId = <your client id>
String password = <your password>

// use adal to Authenticate
AuthenticationContext authContext = null;
AuthenticationResult authResult = null;
ExecutorService service = null;

try {
    service = Executors.newFixedThreadPool(1);
    String url = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
    authContext = new AuthenticationContext(url,
                                            false,
                                            service);
        ClientCredential clientCred = new ClientCredential(clientId, password);
        Future<AuthenticationResult>  future = authContext.acquireToken(
                                                        "https://management.azure.com/",
                                                        clientCred,
                                                        null);
    authResult = future.get();
} catch (Exception ex) {
    // handle exception as needed
} finally {
    service.shutdown();
}

In both cases, assuming everything worked ok, you end up with a valid AuthenticationResult object. This object, for purposes of this example and simpler scenarios like this one, the method to know is:

public final class AuthenticationResult implements Serializable {

    ...

    public String getAccessToken() {
        return accessToken;
    }

    ...
}

The getAccessToken method returns a string you need to include in the headers of any REST calls you make to Azure Resource Manager. Specifically, using the above examples, the token is for performing operations located at the URL https://management.azure.com.

If one were manually constructing the HTTP headers for a REST call, say you wanted to get the list of providers for your subscription (docs for this API are located here). The headers would resemble:

GET /subscriptions/d1188e07-7c04-41b6-8765-9d8fc3c5fe2a/providers?api-version=2014-04-01-preview HTTP/1.1
Content-Type        application/json; charset=utf-8
Authorization       Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuY29yZS53aW5kb3dzLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9iMzY4ZmFkOS0zOTU1LTRiYmMtOGYx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mcl6c0gdr0ZtTBCXav24whAnIRLdEg7OHTM2Ofl6_XnpKWPDmTy8oilY_EvAVSIo4Jd-1MKiqZKokBkmuxjH3_XVl9n3FldfPTbkBFtD3OYXUE7JSGDkyMx2Q
host        management.azure.com
Connection  close

Note the the line starting Authorization, it is using what is referred to as a Bearer Token. The nitty gritty of what a Bearer Token is can be found here.

Code Examples and Other Notes

Right now, the best way to find out more about the ADAL library for Java is to look at the source code or search for other examples using your favorite search engine. The Github repository for ADAL is here.

I provide a working example of the code snippets above on github in azure-rest-examples. Within the authentication/java sub-directory is ApplicationAuthExample.java that does the exact REST call illustrated in the GET request above.