首页 > 解决方案 > 如何在发布映射 URL 中传递tenant_id

问题描述

在邮递员中有以下 URL 以获取访问令牌。

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

现在编写java代码来做我在邮递员中做的同样的事情。
这是示例代码

公共类请求测试{

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());

}

}

但不知何故,URL 没有正确形成,因为我看到以下错误:

400{"error":"invalid_request","error_description":"AADSTS900023: 指定的租户标识符 ':tenant_id' 既不是有效的 DNS 名称,也不是有效的外部域。\r\n跟踪 ID: 652e1996-1863-4183-aac5 -ee9a74680600\r\n相关 ID: 45396fd8-ee9c-423b-ae5d-3bf8885d4532\r\n时间戳: 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"}

请建议我在代码中缺少的地方?请提供任何参考资料。谢谢

标签: javaazurepostman

解决方案


请求url错误,去掉就好:了,应该是

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


推荐阅读