由于Microsoft已宣布,使用基本身份验证访问Outlook IMAP邮箱将很快不再可能,我正试图找出如何在Java中使用OAUTH2正确打开IMAP邮箱。但我总是得到错误代码“A1 NO AUTHENTICATE failed”。
我正在做的事情如下:
我有一个生成OAUTH2访问令牌的方法:
public String getAuthToken(String tanantId,String clientId,String client_secret) throws ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost loginPost = new HttpPost("https://login.microsoftonline.com/" + tanantId + "/oauth2/v2.0/token");
String scopes = "https://outlook.office365.com/.default";
String encodedBody = "client_id=" + clientId + "&scope=" + scopes + "&client_secret=" + client_secret
+ "&grant_type=client_credentials";
loginPost.setEntity(new StringEntity(encodedBody, ContentType.APPLICATION_FORM_URLENCODED));
loginPost.addHeader(new BasicHeader("cache-control", "no-cache"));
CloseableHttpResponse loginResponse = client.execute(loginPost);
InputStream inputStream = loginResponse.getEntity().getContent();
byte[] response = readAllBytes(inputStream);
ObjectMapper objectMapper = new ObjectMapper();
JavaType type = objectMapper.constructType(
objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, String.class));
Map<String, String> parsed = new ObjectMapper().readValue(response, type);
return parsed.get("access_token");
}
生成的令牌似乎是有效的,因为jwt.ms允许我对令牌进行解码。
我尝试使用访问令牌通过XOAUTH2访问邮箱,如下所示:
Properties props = new Properties();
props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", "outlook.office365.com");
props.put("mail.imap.port", "993");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.auth", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.imap.user", mailAddress);
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");
// open mailbox....
String token = getAuthToken(tanantId,clientId,client_secret);
Session session = Session.getInstance(props);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect("outlook.office365.com", mailAddress, token);
但结果总是AuthenticationFailedException
:
* OK The Microsoft Exchange IMAP4 service is ready. [...............AA==]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=xxx@yyy.com, password=<non-null>
A1 AUTHENTICATE XOAUTH2 ....E=
A1 NO AUTHENTICATE failed.
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
从this similar question我现在怀疑我的访问令牌实际上有太少的权限访问邮箱。
我该如何澄清这一点呢?例如,当我解码令牌时,我可以看到它不包含scp
或roles
属性。这是否表明令牌是错误的?
1条答案
按热度按时间ezykj2lf1#
我自己来回答我的问题:代码示例是正确的。问题是缺少对提供的
servicePrincipal
的权限。要在office365中创建servicePrincipal,需要使用objectId
。这些任务只能由管理员使用PowerShell脚本执行。这些都与Java无关。Java API非常简单。