Hello,
I’m trying to download e-mails from ews using the Java EWSClient and Oauth2. I implemented the ROPCTokenProvider with authenticates against Microsoft Graph using a certificate. The TokenProvider runs without an exception and returns and oAuthToken. But as soon as EWSClient.getEWSClient is called, I receive an 401 not authorized error.
Here is a simplified snippet:
ITokenProvider tokenProvider = new AzureROPCTokenProviderCertificate(“tenant-id”, “client-id”, “path_to_cert”, “cert_pw”);
OAuthNetworkCredential credentials = new OAuthNetworkCredential(tokenProvider);
EWSClient.useSAAJAPI(true);
IEWSClient client = EWSClient.getEWSClient(“https://outlook.office365.com/EWS/Exchange.asmx”,credentials);
My TokenProvider-Class:
import com.aspose.email.<em>;
import com.microsoft.aad.msal4j.</em>;
import [java.io](http://java.io/).*;
import java.util.Collections;
import java.util.Set;
public class AzureROPCTokenProviderCertificate implements ITokenProvider
{
private String _authrority = “”;
private String _tenant = “”;
private String _clientId = “”;
private String _certificateFullPath = “”;
private String _certPassword = “”;
private Set _scopes = Collections.singleton(“https://outlook.office365.com/.default”);
private OAuthToken _token = null;
public AzureROPCTokenProviderCertificate(String tenant, String clientId, String certificateFullPath, String certPassword)
{
this._tenant = tenant;
this._clientId = clientId;
this._authrority = "https://login.microsoftonline.com/" + this._tenant + "";
this._certificateFullPath = certificateFullPath;
this._certPassword = certPassword;
}
public OAuthToken acquireToken() throws Exception {
if(this._token == null) {
IClientCredential credential = ClientCredentialFactory.createFromCertificate(new FileInputStream(this._certificateFullPath), this._certPassword);
ConfidentialClientApplication cca =
ConfidentialClientApplication
.builder(this._clientId, credential)
.authority(this._authrority)
.build();
IAuthenticationResult result;
ClientCredentialParameters parameters =
ClientCredentialParameters
.builder(this._scopes)
.build();
result = cca.acquireToken(parameters).join();
System.out.println(result.accessToken());
this._token = new OAuthToken(
result.accessToken(),
TokenType.AccessToken,
result.expiresOnDate());
}
return this._token;
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
@Override
public OAuthToken getAccessToken(){
try{
return this.acquireToken();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public OAuthToken getAccessToken(boolean arg0) {
try{
return this.acquireToken();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
The application has the following permissions (of the type application) in Azure:
Mail.ReadWrite
Mail.Send
User.Read.All
I’m using the Aspose Java E-Mail Library 21.1 (unlicensed for testing puroses).
What could be the cause for the 401 error?