当前位置: 首页 > 知识库问答 >
问题:

EWS API to access Office365 with oAuth2

蒯嘉赐
2023-03-14

We have a Daemon application that uses the EWS API to access office365/Exchange server with basic authentication.I am trying to implement the Oauth2.There are a lot of documents.However, they are often out of date and caused more confusion.I followed this document https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-overview, which seems up-to-date.I did the following steps:

 POST /{tenant}/oauth2/v2.0/token HTTP/1.1           
 Host: login.microsoftonline.com
 Content-Type: application/x-www-form-urlencoded

 client_id={myAppClientId}
 &scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
 &client_secret={myAppSecret}
 &grant_type=client_credentials

I got token with

{
"token_type": "Bearer",
"expires_in": 3599,
"ext_expires_in": 3599,
"access_token": "……thetoken…"

}

Call EWS API in my App

package microsoft.exchange.webservices.data;
import java.util.Map;
public final class BearerTokenCredentials extends ExchangeCredentials {

private static final String BEARER_TOKEN_FORMAT_REGEX = "^[-._~+/A-Za-z0-9]+=*$";
private static final String AUTHORIZATION = "Authorization";
private static final String BEARER_AUTH_PREAMBLE = "Bearer ";
private String token;
public String getToken() {
    return token;
}
public BearerTokenCredentials(String bearerToken) {
    if (bearerToken == null) {
        throw new IllegalArgumentException("Bearer token can not be null");
    }
    this.validateToken(bearerToken);
    this.token = bearerToken;
}
protected void validateToken(String bearerToken) throws IllegalArgumentException {
    if (!bearerToken.matches(BEARER_TOKEN_FORMAT_REGEX)) {
        throw new IllegalArgumentException("Bearer token format is invalid.");
    }
}
@Override
public void prepareWebRequest(HttpWebRequest request) {
    Map<String, String> headersMap = request.getHeaders();
    String bearerValue = BEARER_AUTH_PREAMBLE + token;
    headersMap.put(AUTHORIZATION, bearerValue);
    //headersMap.put("X-AnchorMailbox","esj_office365_imap@genesyslab.onmicrosoft.com");
    request.setHeaders(headersMap);
}
ExchangeService service  = new 
ExchangeService(ExchangeVersion.Exchange2010_SP2); //version is 
Exchange2010_SP2
service.setTraceEnabled(true);
BearerTokenCredentials credentials = new BearerTokenCredentials("thetoken");
service.setCredentials(credentials);
service.setUrl(new 
URI(host));//https://outloook.office365.com/EWS/Exchange.asmx
try{
Folder.bind(service, WellKnownFolderName.Inbox); 
}catch(Exception e)
{
//The remote server returned an error: (500)Internal Server Error
}

共有1个答案

令狐昂雄
2023-03-14

The code you use to connect to the Office365 Mailbox still needs to use EWS Impersonation eg

service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailboxName);

Where MailboxName is the Mailbox you want to connect to.

 类似资料:

相关问答

相关文章

相关阅读