package test;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
class ClientCredentialGrantAndConnect {
private static String authority
; private static String clientId
; private static ConfidentialClientApplication app;
setUpSampleData();
try {
BuildConfidentialClientObject();
IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
String usersListFromGraph
= getUsersListFromGraph
(result.
accessToken()); System.
out.
println("\nAccessToken: "+result.
accessToken());
System.
out.
println("Users in the Tenant = " + usersListFromGraph
);
// imap
connectIMAP("ManishPrajapati@SampleOrg2022.onmicrosoft.com",result.accessToken());
doSleep(2000); // wait for 2 seconds before proceeding...
// POP3
connectPOP("ManishPrajapati@SampleOrg2022.onmicrosoft.com", result.accessToken());
// Wait for program Exit !
doSleep(2000);
System.
out.
println("Press any key to exit ...");
System.
out.
println("Oops! We have an exception of type - " + ex.
getClass()); System.
out.
println("Exception message - " + ex.
getMessage()); throw ex;
}
}
private static void BuildConfidentialClientObject
() throws Exception {
// Load properties file and set properties used throughout the sample
app = ConfidentialClientApplication.builder(
clientId,
ClientCredentialFactory.createFromSecret(secret))
.authority(authority)
.build();
}
// SCOPE is always https://o...content-available-to-author-only...e.com/.default
private static IAuthenticationResult getAccessTokenByClientCredentialGrant
() throws Exception {
// With client credentials flows the scope is ALWAYS of the shape "resource/.default", as the
// application permissions need to be set statically (in the portal), and then granted by a tenant administrator
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.get();
}
// try running an API call using currently generated access token
URL url
= new URL("https://graph.microsoft.com/v1.0/users");
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept","application/json");
int httpResponseCode = conn.getResponseCode();
if(httpResponseCode == HTTPResponse.SC_OK) {
StringBuilder response;
response = new StringBuilder();
while (( inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
return response.toString();
} else {
return String.
format("Connection returned HTTP code: %s with message: %s",
httpResponseCode, conn.getResponseMessage());
}
}
/**
* Helper function unique to this sample setting. In a real application these wouldn't be so hardcoded, for example
* different users may need different authority endpoints or scopes
*/
private static void setUpSampleData
() throws IOException { // Load properties file and set properties used throughout the sample
properties.
load(Thread.
currentThread().
getContextClassLoader().
getResourceAsStream("application.properties"));
authority = properties.getProperty("AUTHORITY");
clientId = properties.getProperty("CLIENT_ID");
secret = properties.getProperty("SECRET");
scope = properties.getProperty("SCOPE");
}
// imap
public static void connectIMAP
(String userEmail,
String accessToken
){ System.
out.
println("\n\n *** IMAP *** \n");
String SSL_FACTORY
= "javax.net.ssl.SSLSocketFactory";
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.sasl.enable", "true");
props.put("mail.imap.port", "993");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.imap.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.socketFactory.port", "993");
props.setProperty("mail.imap.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
try {
final Store store = session.getStore("imap");
store.connect("outlook.office365.com",userEmail, accessToken);
if(store.isConnected()){
System.
out.
println("Connection Established using imap protocol successfully !"); }else{
System.
out.
println("Connection didn't got establisted !"); }
e.printStackTrace();
} catch (MessagingException e) { // store.connect()
e.printStackTrace();
}
}
// POP3
public static void connectPOP
(String email,
String accessToken
){
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.ssl.enable", "false");
properties.put("mail.pop3.starttls.enable", "true");
properties.put("mail.pop3.starttls.required", "true");
properties.put("mail.pop3.connectiontimeout", 5000);
properties.put("mail.pop3.timeout", 5000);
properties.put("mail.pop3.partialfetch", false);
properties.put("mail.pop3.auth.mechanisms", "XOAUTH2");
properties.put("mail.pop3.forgettopheaders", "true");
properties.put("mail.pop3.sasl.enable", "true");
properties.put("mail.pop3.sasl.mechanisms", "XOAUTH2");
properties.put("mail.pop3.auth.login.disable", "true");
properties.put("mail.pop3.auth.plain.disable", "true");
properties.put("mail.pop3.auth.plain.disable", "true");
properties.put("mail.debug", "true");
Session session = Session.getInstance(properties);
session.setDebug(true);
try{
Store store = session.getStore("pop3");
store.connect("outlook.office365.com", email, accessToken);
if(store.isConnected()){
System.
out.
println("Connected with POP3 successfully !"); }
e.printStackTrace();
}
}
public static void doSleep(int d){
int delay = d; // number of milliseconds to sleep
long start
= System.
currentTimeMillis(); while(start
>= System.
currentTimeMillis() - delay
); // do nothing }
}