2

I am using Azure Graph API to import users from Azure AD. In the azure portal I have added multiple Applications. I am getting clientId, tenantId from protal and creating a secret key with one year expiry. Using these values I am creating an access_token and using that token connecting to AD. Here is the code

public static String loginUrlPrefix = "https://login.windows.net/";
    public static String loginUrlSufix = "/oauth2/token";
    public static String importUrl = "https://management.core.windows.net/<subscription-id>/services/importexport/";

    @SuppressWarnings("deprecation")
    public static String getToken(String tenantId,String clientId,String encodedSecretKey) {

        try {
            String secretKey = EncryptionUtils.decryptAES(encodedSecretKey);
            secretKey = URLEncoder.encode(secretKey);
            String urltoConnect = loginUrlPrefix+tenantId+loginUrlSufix;
            String payLoad = "resource=https%3A%2F%2Fmanagement.core.windows.net%2F&client_id="+clientId+"&grant_type=client_credentials&client_secret=" + secretKey;
            URL url = new URL(urltoConnect);
            URLConnection connection = null;
            connection = url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
            java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
            wr.write(payLoad);
            wr.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String content;
            String html = "";
            while ((content = br.readLine()) != null) {
                if (!content.equals("") && content.length() != 0)
                    html += content.trim();
            }
            return html;

        } catch (Exception e) {
            e.printStackTrace();
            try {
                throw e;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        return null;
    }


@SuppressWarnings("deprecation")
    public static Boolean testADConnection(String accessToken,String tenant) {

        try {

            URL url = new URL(String.format("https://graph.windows.net/%s/tenantDetails?api-version=2013-04-05", tenant,
                    accessToken));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // Set the appropriate header fields in the request header.
            conn.setRequestProperty("api-version", "2013-04-05");
            conn.setRequestProperty("Authorization","Bearer "+ accessToken);
            conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
            String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
            System.out.println(goodRespStr);
            int responseCode = conn.getResponseCode();
            if(responseCode == 200){
                return true;
            }
            else{
                System.out.println(goodRespStr);
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                throw e;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        return false;
    }

public static void main(String[] args){
String tokenJSON = getToken(tenantId,clientId,secretKey);
        if(tokenJSON != null){
            JSONObject j = (JSONObject) JSONValue.parse(tokenJSON);
            String token = (String) j.get("access_token");
            testADConnection(token,tenantId);
         }
}

This works fine with the first application I added. But when I add a second application with the same configuration and permissions this is not working. I am getting a 403 error

"odata.error": { "code": "Authentication_MissingOrMalformed", "message": { "lang": "en", "value": "Access Token missing or malformed." }, "date": "2016-12-02T07:27:59", }

Tenant Id i am passing same for both the applications (copied from show diagnostics in help menu) client id I am copying whatever is generated in Azure and labelled as Application Id.Secret Key I am generating in Azure portal with 1 year validity.

Jerry
  • 987
  • 4
  • 16
  • 46

0 Answers0