· 9 years ago · Dec 02, 2016, 10:04 AM
1public static String loginUrlPrefix = "https://login.windows.net/";
2 public static String loginUrlSufix = "/oauth2/token";
3 public static String importUrl = "https://management.core.windows.net/<subscription-id>/services/importexport/";
4
5 @SuppressWarnings("deprecation")
6 public static String getToken(String tenantId,String clientId,String encodedSecretKey) {
7
8 try {
9 String secretKey = EncryptionUtils.decryptAES(encodedSecretKey);
10 secretKey = URLEncoder.encode(secretKey);
11 String urltoConnect = loginUrlPrefix+tenantId+loginUrlSufix;
12 String payLoad = "resource=https%3A%2F%2Fmanagement.core.windows.net%2F&client_id="+clientId+"&grant_type=client_credentials&client_secret=" + secretKey;
13 URL url = new URL(urltoConnect);
14 URLConnection connection = null;
15 connection = url.openConnection();
16 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
17 connection.setDoOutput(true);
18 java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
19 wr.write(payLoad);
20 wr.flush();
21 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
22 String content;
23 String html = "";
24 while ((content = br.readLine()) != null) {
25 if (!content.equals("") && content.length() != 0)
26 html += content.trim();
27 }
28 return html;
29
30 } catch (Exception e) {
31 e.printStackTrace();
32 try {
33 throw e;
34 } catch (Exception e1) {
35 e1.printStackTrace();
36 }
37 }
38
39 return null;
40 }
41
42
43@SuppressWarnings("deprecation")
44 public static Boolean testADConnection(String accessToken,String tenant) {
45
46 try {
47
48 URL url = new URL(String.format("https://graph.windows.net/%s/tenantDetails?api-version=2013-04-05", tenant,
49 accessToken));
50 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
51 // Set the appropriate header fields in the request header.
52 conn.setRequestProperty("api-version", "2013-04-05");
53 conn.setRequestProperty("Authorization","Bearer "+ accessToken);
54 conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
55 String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
56 System.out.println(goodRespStr);
57 int responseCode = conn.getResponseCode();
58 if(responseCode == 200){
59 return true;
60 }
61 else{
62 System.out.println(goodRespStr);
63 }
64
65 } catch (Exception e) {
66 e.printStackTrace();
67 try {
68 throw e;
69 } catch (Exception e1) {
70 e1.printStackTrace();
71 }
72 }
73
74 return false;
75 }
76
77public static void main(String[] args){
78String tokenJSON = getToken(tenantId,clientId,secretKey);
79 if(tokenJSON != null){
80 JSONObject j = (JSONObject) JSONValue.parse(tokenJSON);
81 String token = (String) j.get("access_token");
82 testADConnection(token,tenantId);
83 }
84}