Guest User

Untitled

a guest
Nov 19th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. static String tenantId = "xxxxxxxxxxxxxxxxxxxxxxx";
  2. static String username = "xxxxxxxxxxxxxxxxxxxxxxx";
  3. static String password = "xxxxxxxxx";
  4. static String clientId = "xxxxxxxxxxxxxxxxxxxxxxx";
  5. static String resource = "https://dev.sharepoint.com";
  6. static String userEmail = "xxxxxxxxxxxxxxxxxxxxxx";
  7. static String clientSecret = "xxxxxxxxxxxxxxxxxxx";
  8.  
  9. public static void main(String[] args) throws MalformedURLException, IOException {
  10. AuthenticationContext authContext = null;
  11. AuthenticationResult authResult = null;
  12. ExecutorService service = null;
  13.  
  14. try {
  15. service = Executors.newFixedThreadPool(1);
  16. String url = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
  17. authContext = new AuthenticationContext(url, false, service);
  18. ClientCredential credential = new ClientCredential(clientId, clientSecret);
  19. Future<AuthenticationResult> future = authContext.acquireToken(resource, credential, null);
  20.  
  21. authResult = future.get();
  22. System.out.println("get access token: n" + authResult.getAccessToken());
  23. System.out.println("get refresh token: n" + authResult.getRefreshToken());
  24. } catch (Exception ex) {
  25. ex.printStackTrace();
  26. }
  27. // get access token by refresh token
  28. getToken(authResult.getRefreshToken());
  29. }
  30.  
  31. public static void getToken(String refreshToken) throws IOException {
  32.  
  33. String encoding = "UTF-8";
  34. String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
  35. + "&grant_type=refresh_token&resource=https%3A%2F%2Fdev.sharepoint.com";
  36. String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
  37. byte[] data = params.getBytes(encoding);
  38. URL url = new URL(path);
  39. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  40. conn.setRequestMethod("POST");
  41. conn.setDoOutput(true);
  42. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  43. //conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  44. conn.setConnectTimeout(5 * 1000);
  45. OutputStream outStream = conn.getOutputStream();
  46. outStream.write(data);
  47. outStream.flush();
  48. outStream.close();
  49. System.out.println(conn.getResponseCode());
  50. System.out.println(conn.getResponseMessage());
  51.  
  52. BufferedReader br = null;
  53. if (conn.getResponseCode() != 200) {
  54. br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
  55. } else {
  56. br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
  57. }
  58. System.out.println("Response body : " + br.readLine());
  59. }
Add Comment
Please, Sign In to add comment