azureazure-cliazure-java-sdk

azure java sdk for az get token programatically


I am studying the azure java sdk and I did not find a wrapper method for

az account get-access-token --resource api://xxxxx.microsoft.com/YYYY/ZZZZ

This request works properly from windows batch but i cannot run using azure java sdk. I'll appreciate any feedback about how to run this command using azure java sdk

Best Regards, Aurelian


Solution

  • 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
    

    enter image description here

    Token generated at localhost:8080/gettoken successfully.

    enter image description here