需求:读取outlook邮箱下的邮件内容,通过OAuth来实现邮箱认证。
ews-java-api是一个非常好的解决方案,封装了 完整的api接口,可实现各类需求,但是,该方案只考虑了通过用户名和密码的方式来实现认证账户,用户的需求是通过OAuth来实现认证。
以下是官方的解决方案,
Authenticate an EWS application by using OAuth | Microsoft Learn
可以通过ConfidentialClientApplication 类来实现OAuth认证
ConfidentialClientApplication class | Microsoft Learn
springboot集成ews-java-api
<!-- Compiling the EWS Java API -->
<dependency>
<groupId>com.microsoft.ews-java-api</groupId>
<artifactId>ews-java-api</artifactId>
<version>2.0</version>
</dependency>
通过ConfidentialClientApplication类来实现clientId、tenantId、secret三个参数OAuth认证,获取到token。
在本地中创建BearerTokenCredentials类
package microsoft.exchange.webservices.data.credential;
import microsoft.exchange.webservices.data.core.request.HttpWebRequest;
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);
request.setHeaders(headersMap);
}
}
再通过将token引入,后续便可以使用ews-java-api
BearerTokenCredentials credentials = new BearerTokenCredentials(token);
service.setCredentials(credentials);
service.setUrl(new URI("https://" + "outlook.office365.com" + "/EWS/Exchange.asmx"));
service.setImpersonatedUserId(new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAccount));
有问题欢迎评论私信