azure java sdk for az get token programatically:-
You can use the below java spring-boot code to retrieve the access token and it worked for me as follows.
RestApiController.java
package com.myapp.restcall.controller;
import java.util.Collections;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RestApiController {
@GetMapping(value = "/gettoken")
public static String getToken() throws Exception {
String url = "https://login.microsoftonline.com/<tenantID>/oauth2/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> inputMap = new LinkedMultiValueMap<>();
inputMap.add("grant_type", "client_credentials");
inputMap.add("client_id", "CLIENT_ID");
inputMap.add("client_secret", "CLIENT_SECRET");
inputMap.add("resource", "https://management.core.windows.net/");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(inputMap,
headers);
RestTemplate template = new RestTemplate();
ResponseEntity<String> response = template.postForEntity(url, entity, String.class);
JSONObject myjson = new JSONObject(response.getBody());
String data = (String) myjson.get("access_token");
System.out.println(data);
String access_token = data;
return access_token;
}
}
Replace CLIENT_ID, CLIENT_SECRET & TENANT_ID
in the above java code before executing it.
To build the program, use below commands in the IDE terminal.
mvn clean install
mvn spring-boot:run

Token generated at localhost:8080/gettoken
successfully.
