'ClientAuthenticationException using MS Graph API and Java
I have an issue with sending mails using MS Graph API. Here`s my code:
public GraphMailUtil(){
getConfiguration();
this.graphClient = configureGraphClient();
}
private GraphServiceClient configureGraphClient(){
UsernamePasswordCredential usernamePasswordCredential = initCredential();
TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(SCOPES, usernamePasswordCredential);
return GraphServiceClient.builder().authenticationProvider(tokenCredentialAuthProvider).buildClient();
}
private UsernamePasswordCredential initCredential(){
return new UsernamePasswordCredentialBuilder()
.clientId(CLIENTID)
.username(SENDEREMAIL)
.password(PASSWORD)
.build();
}
public void sendMail(String attachmentFileName) throws IOException {
Message message = composeMessage(attachmentFileName);
graphClient.users(SENDEREMAIL)
.sendMail(UserSendMailParameterSet
.newBuilder()
.withMessage(message)
.withSaveToSentItems(null)
.build())
.buildRequest()
.post();
}
At run time I have an exception:
com.microsoft.graph.core.ClientException: Error executing the request
Caused by: com.azure.core.exception.ClientAuthenticationException: Failed to acquire token with username and password.
Caused by: com.microsoft.aad.msal4j.MsalClientException: Error parsing WSTrustResponse: Unable to find any tokens
All the data I provide to authenticate is correct, I`ve checked it for 100 times. Does anyone has an idea what is the reason?
Solution 1:[1]
After some research I decided not to use MS libraries at all. Firstly, it caused dependency conflicts which were pain in the neck to resolve.
Secondly, UsernamePasswordCredential set for my app was not usable.
Now I just create two separate POST requests: one for retrieving token, one for sending an email. I use HttpURLConnection from java.net,*.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rkomissarov |