fork(5) download
  1. package test;
  2. import com.microsoft.aad.msal4j.ClientCredentialFactory;
  3. import com.microsoft.aad.msal4j.ClientCredentialParameters;
  4. import com.microsoft.aad.msal4j.ConfidentialClientApplication;
  5. import com.microsoft.aad.msal4j.IAuthenticationResult;
  6. import com.nimbusds.oauth2.sdk.http.HTTPResponse;
  7.  
  8. import java.io.BufferedReader;
  9. import java.io.IOException;
  10. import java.io.InputStreamReader;
  11. import java.net.HttpURLConnection;
  12. import java.net.URL;
  13. import java.util.Base64;
  14. import java.util.Collections;
  15. import java.util.Properties;
  16. import java.util.concurrent.CompletableFuture;
  17.  
  18. import javax.mail.MessagingException;
  19. import javax.mail.NoSuchProviderException;
  20. import javax.mail.Session;
  21. import javax.mail.Store;
  22.  
  23. class ClientCredentialGrantAndConnect {
  24.  
  25. private static String authority;
  26. private static String clientId;
  27. private static String secret;
  28. private static String scope;
  29. private static ConfidentialClientApplication app;
  30.  
  31. public static void main(String args[]) throws Exception{
  32.  
  33. setUpSampleData();
  34.  
  35. try {
  36. BuildConfidentialClientObject();
  37. IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
  38. String usersListFromGraph = getUsersListFromGraph(result.accessToken());
  39. System.out.println("\nAccessToken: "+result.accessToken());
  40.  
  41. System.out.println("Users in the Tenant = " + usersListFromGraph);
  42.  
  43.  
  44. // imap
  45. connectIMAP("ManishPrajapati@SampleOrg2022.onmicrosoft.com",result.accessToken());
  46.  
  47. doSleep(2000); // wait for 2 seconds before proceeding...
  48.  
  49. // POP3
  50. connectPOP("ManishPrajapati@SampleOrg2022.onmicrosoft.com", result.accessToken());
  51.  
  52.  
  53. // Wait for program Exit !
  54. doSleep(2000);
  55. System.out.println("Press any key to exit ...");
  56. System.in.read();
  57.  
  58. } catch(Exception ex){
  59. System.out.println("Oops! We have an exception of type - " + ex.getClass());
  60. System.out.println("Exception message - " + ex.getMessage());
  61. throw ex;
  62. }
  63. }
  64.  
  65. private static void BuildConfidentialClientObject() throws Exception {
  66.  
  67. // Load properties file and set properties used throughout the sample
  68. app = ConfidentialClientApplication.builder(
  69. clientId,
  70. ClientCredentialFactory.createFromSecret(secret))
  71. .authority(authority)
  72. .build();
  73. }
  74.  
  75.  
  76. // SCOPE is always https://o...content-available-to-author-only...e.com/.default
  77. private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
  78.  
  79. // With client credentials flows the scope is ALWAYS of the shape "resource/.default", as the
  80. // application permissions need to be set statically (in the portal), and then granted by a tenant administrator
  81. ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
  82. Collections.singleton(scope))
  83. .build();
  84.  
  85. CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
  86. return future.get();
  87. }
  88.  
  89.  
  90. // try running an API call using currently generated access token
  91. private static String getUsersListFromGraph(String accessToken) throws IOException {
  92. URL url = new URL("https://graph.microsoft.com/v1.0/users");
  93. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  94.  
  95. conn.setRequestMethod("GET");
  96. conn.setRequestProperty("Authorization", "Bearer " + accessToken);
  97. conn.setRequestProperty("Accept","application/json");
  98.  
  99. int httpResponseCode = conn.getResponseCode();
  100. if(httpResponseCode == HTTPResponse.SC_OK) {
  101.  
  102. StringBuilder response;
  103. new InputStreamReader(conn.getInputStream()))){
  104.  
  105. String inputLine;
  106. response = new StringBuilder();
  107. while (( inputLine = in.readLine()) != null) {
  108. response.append(inputLine);
  109. }
  110. }
  111. return response.toString();
  112. } else {
  113. return String.format("Connection returned HTTP code: %s with message: %s",
  114. httpResponseCode, conn.getResponseMessage());
  115. }
  116. }
  117.  
  118. /**
  119.   * Helper function unique to this sample setting. In a real application these wouldn't be so hardcoded, for example
  120.   * different users may need different authority endpoints or scopes
  121.   */
  122. private static void setUpSampleData() throws IOException {
  123. // Load properties file and set properties used throughout the sample
  124. Properties properties = new Properties();
  125. properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"));
  126.  
  127. authority = properties.getProperty("AUTHORITY");
  128. clientId = properties.getProperty("CLIENT_ID");
  129. secret = properties.getProperty("SECRET");
  130. scope = properties.getProperty("SCOPE");
  131. }
  132.  
  133.  
  134. // imap
  135. public static void connectIMAP(String userEmail, String accessToken){
  136. System.out.println("\n\n *** IMAP *** \n");
  137.  
  138. String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  139. Properties props= new Properties();
  140.  
  141. props.put("mail.imap.ssl.enable", "true");
  142. props.put("mail.imap.sasl.enable", "true");
  143. props.put("mail.imap.port", "993");
  144.  
  145. props.put("mail.imap.auth.mechanisms", "XOAUTH2");
  146. props.put("mail.imap.sasl.mechanisms", "XOAUTH2");
  147.  
  148. props.put("mail.imap.auth.login.disable", "true");
  149. props.put("mail.imap.auth.plain.disable", "true");
  150.  
  151. props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
  152. props.setProperty("mail.imap.socketFactory.fallback", "false");
  153. props.setProperty("mail.imap.socketFactory.port", "993");
  154. props.setProperty("mail.imap.starttls.enable", "true");
  155.  
  156. props.put("mail.debug", "true");
  157. props.put("mail.debug.auth", "true");
  158.  
  159. Session session = Session.getInstance(props);
  160. session.setDebug(true);
  161.  
  162.  
  163. try {
  164. final Store store = session.getStore("imap");
  165. store.connect("outlook.office365.com",userEmail, accessToken);
  166.  
  167. if(store.isConnected()){
  168. System.out.println("Connection Established using imap protocol successfully !");
  169. }else{
  170. System.out.println("Connection didn't got establisted !");
  171. }
  172. } catch (NoSuchProviderException e) { // session.getStore()
  173. e.printStackTrace();
  174. } catch (MessagingException e) { // store.connect()
  175. e.printStackTrace();
  176. }
  177. }
  178.  
  179.  
  180. // POP3
  181. public static void connectPOP(String email, String accessToken){
  182. Properties properties= new Properties();
  183.  
  184. properties.put("mail.pop3.port", "995");
  185.  
  186. properties.put("mail.pop3.ssl.enable", "false");
  187. properties.put("mail.pop3.starttls.enable", "true");
  188. properties.put("mail.pop3.starttls.required", "true");
  189.  
  190. properties.put("mail.pop3.connectiontimeout", 5000);
  191. properties.put("mail.pop3.timeout", 5000);
  192. properties.put("mail.pop3.partialfetch", false);
  193. properties.put("mail.pop3.auth.mechanisms", "XOAUTH2");
  194.  
  195. properties.put("mail.pop3.forgettopheaders", "true");
  196. properties.put("mail.pop3.sasl.enable", "true");
  197. properties.put("mail.pop3.sasl.mechanisms", "XOAUTH2");
  198. properties.put("mail.pop3.auth.login.disable", "true");
  199. properties.put("mail.pop3.auth.plain.disable", "true");
  200. properties.put("mail.pop3.auth.plain.disable", "true");
  201. properties.put("mail.debug", "true");
  202.  
  203. Session session = Session.getInstance(properties);
  204. session.setDebug(true);
  205. try{
  206. Store store = session.getStore("pop3");
  207. store.connect("outlook.office365.com", email, accessToken);
  208.  
  209. if(store.isConnected()){
  210. System.out.println("Connected with POP3 successfully !");
  211. }
  212. }catch(Exception e){
  213. e.printStackTrace();
  214. }
  215. }
  216.  
  217. public static void doSleep(int d){
  218. int delay = d; // number of milliseconds to sleep
  219. long start = System.currentTimeMillis();
  220. while(start >= System.currentTimeMillis() - delay); // do nothing
  221. }
  222.  
  223. }
  224.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:2: error: package com.microsoft.aad.msal4j does not exist
import com.microsoft.aad.msal4j.ClientCredentialFactory;
                               ^
Main.java:3: error: package com.microsoft.aad.msal4j does not exist
import com.microsoft.aad.msal4j.ClientCredentialParameters;
                               ^
Main.java:4: error: package com.microsoft.aad.msal4j does not exist
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
                               ^
Main.java:5: error: package com.microsoft.aad.msal4j does not exist
import com.microsoft.aad.msal4j.IAuthenticationResult;
                               ^
Main.java:6: error: package com.nimbusds.oauth2.sdk.http does not exist
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
                                   ^
Main.java:18: error: package javax.mail does not exist
import javax.mail.MessagingException;
                 ^
Main.java:19: error: package javax.mail does not exist
import javax.mail.NoSuchProviderException;
                 ^
Main.java:20: error: package javax.mail does not exist
import javax.mail.Session;
                 ^
Main.java:21: error: package javax.mail does not exist
import javax.mail.Store;
                 ^
Main.java:29: error: cannot find symbol
    private static ConfidentialClientApplication app;
                   ^
  symbol:   class ConfidentialClientApplication
  location: class ClientCredentialGrantAndConnect
Main.java:77: error: cannot find symbol
    private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
                   ^
  symbol:   class IAuthenticationResult
  location: class ClientCredentialGrantAndConnect
Main.java:37: error: cannot find symbol
            IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
            ^
  symbol:   class IAuthenticationResult
  location: class ClientCredentialGrantAndConnect
Main.java:68: error: cannot find symbol
    	app = ConfidentialClientApplication.builder(
    	      ^
  symbol:   variable ConfidentialClientApplication
  location: class ClientCredentialGrantAndConnect
Main.java:70: error: cannot find symbol
                ClientCredentialFactory.createFromSecret(secret))
                ^
  symbol:   variable ClientCredentialFactory
  location: class ClientCredentialGrantAndConnect
Main.java:81: error: cannot find symbol
        ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
        ^
  symbol:   class ClientCredentialParameters
  location: class ClientCredentialGrantAndConnect
Main.java:81: error: cannot find symbol
        ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
                                                           ^
  symbol:   variable ClientCredentialParameters
  location: class ClientCredentialGrantAndConnect
Main.java:85: error: cannot find symbol
        CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
                          ^
  symbol:   class IAuthenticationResult
  location: class ClientCredentialGrantAndConnect
Main.java:100: error: cannot find symbol
        if(httpResponseCode == HTTPResponse.SC_OK) {
                               ^
  symbol:   variable HTTPResponse
  location: class ClientCredentialGrantAndConnect
Main.java:160: error: cannot find symbol
		Session session = Session.getInstance(props);
		^
  symbol:   class Session
  location: class ClientCredentialGrantAndConnect
Main.java:160: error: cannot find symbol
		Session session = Session.getInstance(props);
		                  ^
  symbol:   variable Session
  location: class ClientCredentialGrantAndConnect
Main.java:165: error: cannot find symbol
			final Store store = session.getStore("imap");					
			      ^
  symbol:   class Store
  location: class ClientCredentialGrantAndConnect
Main.java:173: error: cannot find symbol
		} catch (NoSuchProviderException e) {	// session.getStore()
		         ^
  symbol:   class NoSuchProviderException
  location: class ClientCredentialGrantAndConnect
Main.java:175: error: cannot find symbol
		} catch (MessagingException e) {		// store.connect()
		         ^
  symbol:   class MessagingException
  location: class ClientCredentialGrantAndConnect
Main.java:204: error: cannot find symbol
        Session session = Session.getInstance(properties);
        ^
  symbol:   class Session
  location: class ClientCredentialGrantAndConnect
Main.java:204: error: cannot find symbol
        Session session = Session.getInstance(properties);
                          ^
  symbol:   variable Session
  location: class ClientCredentialGrantAndConnect
Main.java:207: error: cannot find symbol
	        Store store = session.getStore("pop3");
	        ^
  symbol:   class Store
  location: class ClientCredentialGrantAndConnect
26 errors
stdout
Standard output is empty