0
votes

Have following URL in postman to get the access token.

https://login.microsoftonline.com/:tenant_id/oauth2/token

now writing java code to do the same thing which I am doing in postman.
here is the sample code

public class RequestTest {

public static void main(String[] args) throws IOException, InterruptedException {
    // TODO Auto-generated method stub
    
    String tenant_id = "<tenant_id>";
    
    String keys = "<client_id>:<client_secret>";
    String url = "https://login.microsoftonline.com/:" + tenant_id + "/oauth2/token";
    
    HashMap<String, String> parameters = new HashMap<>();
    parameters.put("grant_type", "client_credentials");
            
    String form = parameters.keySet().stream().map(key -> key + "=" + URLEncoder.encode(parameters.get(key),StandardCharsets.UTF_8)).collect(Collectors.joining("&"));

    String encoding = Base64.getEncoder().encodeToString(keys.getBytes());
    
    HttpClient client = HttpClient.newHttpClient();

    HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
            .headers("Content-Type", "application/x-www-form-urlencoded", "Authorization", "Basic "+encoding)
            .POST(BodyPublishers.ofString(form)).build();
    HttpResponse<?> response = client.send(request, BodyHandlers.ofString());
    System.out.println(response.statusCode() + response.body().toString());

}

}

but somehow the URL is not getting formed properly as i am seeing following error :

400{"error":"invalid_request","error_description":"AADSTS900023: Specified tenant identifier ':tenant_id' is neither a valid DNS name, nor a valid external domain.\r\nTrace ID: 652e1996-1863-4183-aac5-ee9a74680600\r\nCorrelation ID: 45396fd8-ee9c-423b-ae5d-3bf8885d4532\r\nTimestamp: 2021-04-15 09:24:51Z","error_codes":[900023],"timestamp":"2021-04-15 09:24:51Z","trace_id":"652e1996-1863-4183-aac5-ee9a74680600","correlation_id":"45396fd8-ee9c-423b-ae5d-3bf8885d4532","error_uri":"https://login.microsoftonline.com/error?code=900023"}

please suggest where i am missing in the code ? any references please . Thanks

1

1 Answers

1
votes

The request url is wrong, just remove : from it, it should be

https://login.microsoftonline.com/" + tenant_id + "/oauth2/token