Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crpietschmann/02a74d618a7ffc2503668490b1eb0b36 to your computer and use it in GitHub Desktop.
Save crpietschmann/02a74d618a7ffc2503668490b1eb0b36 to your computer and use it in GitHub Desktop.
Authenticate and Call the Azure Resource Manager (ARM) REST API from Java - Service to Service Authentication
package javaapplication1;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
// https://hc.apache.org/
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
// https://www.java2s.com/Code/JarDownload/java/java-json.jar.zip
import org.json.*;
/**
*
* @author demouser
*/
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, JSONException, Exception {
String tenantId = "azure-ad-tenant-id"; // Azure AD Tenant ID
String subscriptionId = "azure-subscription-id"; // Azure Subscription ID
String appId = "azure-ad-application-id"; // Application ID
String appKey = "azure-ad-application-key"; // Application Key
HttpClient httpclient = HttpClients.createDefault();
System.out.println("Getting Acess Token from Azure AD...");
try {
URIBuilder authTokenBuilder = new URIBuilder(
"https://login.microsoftonline.com/" + tenantId + "/oauth2/token"
);
/*
References:
https://docs.microsoft.com/en-us/rest/api/azure/#create-the-request
https://docs.microsoft.com/en-us/rest/api/azure/#register-your-client-application-with-azure-ad
https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-application-objects
https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal
*/
// setup HttpPost request
URI authTokenUri = authTokenBuilder.build();
HttpPost authTokenRequest = new HttpPost(authTokenUri);
// add required query parameterss
List <NameValuePair> authTokenParams = new ArrayList <NameValuePair>();
authTokenParams.add(new BasicNameValuePair("grant_type", "client_credentials"));
authTokenParams.add(new BasicNameValuePair("client_id", appId));
authTokenParams.add(new BasicNameValuePair("client_secret", appKey));
authTokenParams.add(new BasicNameValuePair("resource", "https://management.core.windows.net")); //https://graph.windows.net"));
authTokenRequest.setEntity(new UrlEncodedFormEntity(authTokenParams));
HttpResponse authTokenResponse = httpclient.execute(authTokenRequest);
HttpEntity authTokenEntity = authTokenResponse.getEntity();
if (authTokenEntity == null) {
throw new Exception("authTokenEntity is null");
}
String authTokenJsonRaw = EntityUtils.toString(authTokenEntity);
System.out.println("Raw JSON: " + authTokenJsonRaw);
System.out.println("");
// parse out Access Token from JSON
JSONObject authTokenJson = new JSONObject(authTokenJsonRaw);
if (authTokenJson.has("error")) {
System.out.println("ERROR RECEIVED: " + authTokenJson.getString("error"));
System.out.println(authTokenJson.getString("error_description"));
return;
}
String access_token = authTokenJson.getString("access_token");
// Output values from the Response JSON to the terminal
System.out.println("access_token: " + access_token);
System.out.println("token_type: " + authTokenJson.getString("token_type"));
System.out.println("expires_in: " + authTokenJson.getString("expires_in"));
URIBuilder builder = new URIBuilder("https://management.azure.com/subscriptions/" + subscriptionId + "/resourcegroups");
builder.setParameter("api-version", "2018-02-01");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.addHeader("Authorization", "Bearer " + access_token);
System.out.println("Get All Resource Groups in Azure Subscription...");
HttpResponse response = httpclient.execute(request);
System.out.println("HTTP Status Code: " + response.getStatusLine());
HttpEntity entity = response.getEntity();
String json = "";
if (entity != null){
json = EntityUtils.toString(entity);
System.out.println("JSON: " + json);
System.out.println("");
// Output list of Resource Groups to console
JSONObject parsedJson = new JSONObject(json);
JSONArray resourceGroups = parsedJson.getJSONArray("value");
for(int i = 0; i < resourceGroups.length(); i++){
JSONObject group = resourceGroups.getJSONObject(i);
System.out.println("Reource Group Name: " + group.getString("name"));
System.out.println("Location: " + group.getString("location"));
System.out.println("");
}
}
} catch (URISyntaxException ex) {
System.out.println(ex.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment