猿问

从 Azure AD Java 获取访问令牌

我想通过 Billing REST Api 获得 Azure RateCard Json 响应。为此,我在 Eclipse 中使用以下代码:


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;


import com.fasterxml.jackson.core.JsonFactory;

import com.fasterxml.jackson.core.JsonParser;

import com.fasterxml.jackson.core.JsonToken;


public class RateCardRest {


public static String getAccessToken(String tenantId, String clientId, String clientSecret)

        throws MalformedURLException, IOException {

    String endpoint = String.format("https://login.microsoftonline.com/%s/oauth2/token", tenantId);

    String postBody = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&resource=%s",

            clientId, clientSecret, "https://management.azure.com/");

    HttpURLConnection conn = (HttpURLConnection) new URL(endpoint).openConnection();

    conn.setRequestMethod("POST");

    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.setDoOutput(true);

    conn.getOutputStream().write(postBody.getBytes());

    conn.connect();

//      If you want to see the response content, please use the commented code below.

//      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

//      StringBuilder builder = new StringBuilder();

//      String line = null;

//      while ((line = reader.readLine()) != null) {

//          builder.append(line);

//      }

//      reader.close();

//      System.out.println(builder.toString());

//      The output for access token is 

        String name = parser.getCurrentName();

        if ("access_token".equals(name)) {

            parser.nextToken();

            accessToken = parser.getText();

        }

    }

    return accessToken;

}

当我搜索 URL 时,我收到以下消息:


AADSTS900561:端点只接受 POST、OPTIONS 请求。收到一个 GET 请求。


慕标5832272
浏览 124回答 1
1回答

POPMUISE

您需要对在 AAD 中生成的客户端密钥进行 UrlEncode。clientSecret=java.net.URLEncoder.encode(clientSecret,"UTF-8");下面到String&nbsp;clientSecret&nbsp;=&nbsp;"<your&nbsp;client&nbsp;secret&nbsp;key&nbsp;generated&nbsp;in&nbsp;AAD>";
随时随地看视频慕课网APP

相关分类

Java
我要回答