项目需求:
以证书认证获取授权调用MS Graph API发送邮件,代替原有的SMTP协议以用户名密码认证的方式。
操作步骤:
1.在Microsoft Azure 应用中心注册你的应用,申请需要使用的api权限
注册好后你会得到如下信息:
在权限中添加你需要的,发送邮件的如下:
到这里基本注册流程结束。
2.上代码
(这个api的java示例不好使,我也调了很久没调通,就用了Http方式实现)
首先在你的项目配置中加入
<dependency>
<groupId>com.microsoft.graph</groupId>
<artifactId>microsoft-graph</artifactId>
<version>[5.0,)</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>[1.3,)</version>
</dependency>
加好后通过证书换取授权令牌
/**
* 授权令牌初始化
*/
protected void initToken(String sendMail) {
try {
//匹配clientId
InputStream resource = new FileUtil().getResource(crtUrl.concat("applicationId.json"));
String fileStr = FileUtil.getFileStr(resource);
if (Objects.isNull(resource)) {
throw new BwCustomizeBizException("用户邮箱信息读取异常:配置文件不存在");
}
BaseMailInfo mailInfo = new BaseMailInfo();
List<BaseMailInfo> mailInfos = JSONArray.parseArray(fileStr, BaseMailInfo.class);
if (null != mailInfos && !mailInfos.isEmpty()) {
mailInfo = mailInfos.stream().filter(x -> x.getMail().equals(sendMail)).findFirst().orElse(null);
}
if (Objects.isNull(mailInfo)) {
log.error("未获取到邮箱:{} 的配置信息,请检查applicationId.json配置文件", sendMail);
throw new BwCustomizeBizException("MS graph 邮箱未注册,请更新配置文件");
}
client_id = mailInfo.getApplication_id();
//匹配私钥和证书
keyPath = crtUrl.concat(sendMail).concat(".der");
certPath = crtUrl.concat(sendMail).concat(".crt");
//设置令牌
buildConfidentialClientObject();
IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
accessToken = result.accessToken();
log.info("【Microsoft_Graph_mail】 - get the accessToken = {}", accessToken);
} catch (Exception ex) {
log.error("【Microsoft_Graph_mail】 - 授权认证失败:{}", ex.getStackTrace());
throw new BwCustomizeBizException("授权认证失败:" + ex.getMessage());
}
}
//项目发布后是Jar包形式,需要以getResourceAsStream方法获取jar中的文件
public InputStream getResource(String fileName) throws IOException{
return this.getClass().getClassLoader().getResourceAsStream(fileName);
}
applicationId.json 文件我放在根目录,数据格式为json,支持多个证书配置
[
{
"index": 1,
"mail": "....com",
"application_id": "...",
"application_owner": "..."
},
{
"index": 2,
"mail": "....com",
"application_id": "...",
"application_owner": "..."
},
{
"index": 3,
"mail": "....com",
"application_id": "...",
"application_owner": "..."
}
]
证书也放在根目录下了,以及根据证书.crt通过openssl 生成的秘钥文件.der, 其中.crt文件没用到
继续上代码:方法buildConfidentialClientObject()
/**
* 创建认证客户端
*
* @throws Exception
*/
private void buildConfidentialClientObject() throws Exception {
InputStream keyResoutce = new FileUtil().getResource(keyPath);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(FileUtil.read(keyResoutce));
PrivateKey key = KeyFactory.getInstance("RSA").generatePrivate(spec);
InputStream certStream = new FileUtil().getResource(certPath);
X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certStream);
app = ConfidentialClientApplication.builder(
client_id,
ClientCredentialFactory.createFromCertificate(key, cert))
.authority(authority)
.build();
}
方法
getAccessTokenByClientCredentialGrant()
/**
* 获取授权令牌
* 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
*/
private IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
Collections.singleton(scope))
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.get();
}
到此授权已经ok了,后面发邮件方法及读取邮件等等其他的,都可以这个令牌操作,再贴个完整方法吧,学弟们可以直接用哈哈。。。
/**
* MS graph api 邮箱实现辅助类
*/
@Service
@Slf4j
public class MSGraphHandler {
//应用ID
private static String client_id = "";
//私钥存放目录
private static String keyPath = "";
//证书存放目录
private static String certPath = "";
//邮箱客户端访问令牌
private static String accessToken = "";
@Value("${msgraphMail.authority}")
private String authority;
@Value("${msgraphMail.scope}")
private String scope;
@Value("${msgraphMail.sendAddress}")
private String sendAddress;
@Value("${msgraphMail.crtUrl}")
private String crtUrl;
private static ConfidentialClientApplication app;
/**
* 发送邮件
*/
public void sendGraphMail(GraphMessageDTO message, String sendMail) {
try {
initToken(sendMail);
if (StringUtils.isBlank(accessToken)) {
throw new BwCustomizeBizException("【Microsoft_Graph_mail】 - 授权认证失败: accessToken不存在");
}
sendAddress = sendAddress.replace("%%", sendMail);
//组成邮件内容
GraphMailDTO<GraphMessageDTO> graphMailDTO = new GraphMailDTO();
graphMailDTO.setMessage(message);
graphMailDTO.setSaveToSentItems("true");
log.info("【Microsoft_Graph_mail】打印邮件内容:{}", JSON.toJSONString(graphMailDTO));
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000);// 设置超时
requestFactory.setReadTimeout(10000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Authorization", "Bearer " + accessToken);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(graphMailDTO), httpHeaders);
ResponseEntity<String> responseEntity = restTemplate.exchange(sendAddress, HttpMethod.POST, httpEntity, String.class);
log.info("【Microsoft_Graph_mail】获取发送结果:{}", JSON.toJSONString(responseEntity));
} catch (Exception e) {
throw new BwCustomizeBizException("邮件发送失败:" + e.getMessage());
}
}
/**
* 授权令牌初始化
*/
protected void initToken(String sendMail) {
try {
//匹配clientId
InputStream resource = new FileUtil().getResource(crtUrl.concat("applicationId.json"));
String fileStr = FileUtil.getFileStr(resource);
if (Objects.isNull(resource)) {
throw new BwCustomizeBizException("用户邮箱信息读取异常:配置文件不存在");
}
BaseMailInfo mailInfo = new BaseMailInfo();
List<BaseMailInfo> mailInfos = JSONArray.parseArray(fileStr, BaseMailInfo.class);
if (null != mailInfos && !mailInfos.isEmpty()) {
mailInfo = mailInfos.stream().filter(x -> x.getMail().equals(sendMail)).findFirst().orElse(null);
}
if (Objects.isNull(mailInfo)) {
log.error("未获取到邮箱:{} 的配置信息,请检查applicationId.json配置文件", sendMail);
throw new BwCustomizeBizException("MS graph 邮箱未注册,请更新配置文件");
}
client_id = mailInfo.getApplication_id();
//匹配私钥和证书
keyPath = crtUrl.concat(sendMail).concat(".der");
certPath = crtUrl.concat(sendMail).concat(".crt");
//设置令牌
buildConfidentialClientObject();
IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
accessToken = result.accessToken();
log.info("【Microsoft_Graph_mail】 - get the accessToken = {}", accessToken);
} catch (Exception ex) {
log.error("【Microsoft_Graph_mail】 - 授权认证失败:{}", ex.getStackTrace());
throw new BwCustomizeBizException("授权认证失败:" + ex.getMessage());
}
}
/**
* 创建认证客户端
*
* @throws Exception
*/
private void buildConfidentialClientObject() throws Exception {
InputStream keyResoutce = new FileUtil().getResource(keyPath);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(FileUtil.read(keyResoutce));
PrivateKey key = KeyFactory.getInstance("RSA").generatePrivate(spec);
InputStream certStream = new FileUtil().getResource(certPath);
X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certStream);
app = ConfidentialClientApplication.builder(
client_id,
ClientCredentialFactory.createFromCertificate(key, cert))
.authority(authority)
.build();
}
/**
* 获取授权令牌
* 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
*/
private IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
Collections.singleton(scope))
.build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.get();
}
}
文章来源:https://www.toymoban.com/news/detail-458044.html
以上为本次踩坑日记,希望对你有所帮助!若有不理解的地方欢迎私信。。。文章来源地址https://www.toymoban.com/news/detail-458044.html
到了这里,关于使用证书认证方式调用Microsoft Graph Api发送邮件案例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!