用于 IMAP 和 SMTP 身份验证的 Office 365 XOAUTH2 失败

Office 365 XOAUTH2 for IMAP and SMTP Authentication fails

最近宣布 support for OAuth 2.0 for IMAP and SMTP in the Exchange Online。 在 the guide 之后,我设置了应用程序权限以及 IMAP 和 SMTP 连接。 该应用程序配置为 Accounts in any organizational directory (Any Azure AD directory - Multitenant) 并使用 authorization code flow.

以下 URL 用于授权:

并添加了以下授权的 Microsoft Graph 范围:

范围,来自代码的请求:

final List<String> scopes = Arrays.asList(
    "offline_access",
    "email",
    "openid",
    "profile",
    "User.Read",
    "Mail.ReadWrite",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

我成功收到访问和刷新令牌:

{
    "token_type": "Bearer",
    "scope": "email IMAP.AccessAsUser.All Mail.ReadWrite openid profile SMTP.Send User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "edited",
    "refresh_token": "edited",
    "id_token": "edited"
}

这是用于连接到 IMAP 的代码:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imaps.sasl.enable", "true");
props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

final Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, userEmail, accessToken);

生成以下输出:

DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle]
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: closeFoldersOnStoreFailure
DEBUG IMAPS: trying to connect to host "outlook.office365.com", port 993, isSSL true
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADc...]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
DEBUG IMAPS: AUTH: PLAIN
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=outlook.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS:  XOAUTH2
DEBUG IMAPS: 
DEBUG IMAPS: SASL client XOAUTH2
DEBUG IMAPS: SASL callback length: 2
DEBUG IMAPS: SASL callback 0: javax.security.auth.callback.NameCallback@17046283
DEBUG IMAPS: SASL callback 1: javax.security.auth.callback.PasswordCallback@5bd03f44
A1 AUTHENTICATE XOAUTH2 dXNlcj1o...
A1 NO AUTHENTICATE failed.

Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:732)
    at javax.mail.Service.connect(Service.java:366)

下面的代码用于连接到 SMTP:

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth.login.disable","true");
props.put("mail.smtp.auth.plain.disable","true");
props.put("mail.debug.auth", "true");

Session session = Session.getInstance(props);
session.setDebug(true);

String userEmail = "user@domain.onmicrosoft.com";
String accessToken = "access_token_received_on_previous_step";

Transport transport = session.getTransport("smtp");
transport.connect("smtp.office365.com", 587, userEmail, accessToken);

提供以下输出:

DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 AM5PR0701CA0005.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 4 May 2020 15:52:28 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO ubuntu-B450-AORUS-M
250-AM5PR0701CA0005.outlook.office365.com Hello [my ip here]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, user=user@domain.onmicrosoft.com, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
AUTH XOAUTH2 dXNlcj1obW9kaUB...
535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]

Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [AM5PR0701CA0005.eurprd07.prod.outlook.com]
    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
    at javax.mail.Service.connect(Service.java:366)

我也尝试过:

结果总是一样的。

是我做错了什么,还是微软方面对此的支持存在错误?

更新 1:

从命令行尝试过,但结果相同:

$ openssl s_client -crlf -connect outlook.office365.com:993
... connection part omitted
* OK The Microsoft Exchange IMAP4 service is ready. [QQBNADYAUAAxADkAMgBDAEEAMAAwADkAMQAuAEUAVQBSAFAAMQA5ADIALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
C01 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
C01 OK CAPABILITY completed.
A01 AUTHENTICATE XOAUTH2 dXNlcj1obW9kaUBjb...
A01 NO AUTHENTICATE failed.
* BYE Connection is closed. 13
read:errno=0

更新二:

尝试使用以下权限在 Azure 门户中创建全新的应用程序:

并在尝试同意范围时收到以下屏幕:

这很奇怪,因为 Azure 门户的权限没有指定需要管理员同意,而且我之前的应用程序注册在请求 IMAP 和 SMTP 范围时没有显示这样的屏幕。

更新 3:

感谢对此的评论 post 我尝试了以下范围:

public static final List<String> SCOPES = Arrays.asList(
    "offline_access",
    "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

哪个给了我下面的令牌:

{
    "token_type": "Bearer",
    "scope": "https://outlook.office365.com/IMAP.AccessAsUser.All https://outlook.office365.com/SMTP.Send",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1....",
    "refresh_token": "OAQABAAAAAAAm...."
}

IMAP/SMTP 身份验证成功 我可以阅读收件箱 + 发送电子邮件!

但对于我的应用程序,我还需要几个其他范围来使用某些 MS Graph API 端点(读取用户配置文件、消息订阅和消息删除)。

所以我尝试了不同的范围:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access",
        "User.Read",
        "Mail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

这给出了令牌(请注意范围值与实际工作的令牌不同,权限没有前景 url):

{
    "token_type": "Bearer",
    "scope": "IMAP.AccessAsUser.All Mail.ReadWrite SMTP.Send User.Read profile openid email",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1Q...",
    "refresh_token": "OAQABAAAAAAAm..."
}

这导致了我之前得到的结果:

A1 NO AUTHENTICATE failed.

正在尝试将所有范围作为 URL:

public static final List<String> SCOPES = Arrays.asList(
        "offline_access", // or "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access"
        "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
        "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
        "https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All",
        "https%3A%2F%2Foutlook.office365.com%2FSMTP.Send"
);

导致获取token时出现如下错误(consent步骤成功通过):

{
    "error": "invalid_request",
    "error_description": "AADSTS28000: Provided value for the input parameter scope is not valid because it contains more than one resource. Scope offline_access https://graph.microsoft.com/user.read https://graph.microsoft.com/mail.readwrite https://outlook.office365.com/imap.accessasuser.all https://outlook.office365.com/smtp.send is not valid.\r\nTrace ID: c3282396-6231-4e11-8300-77bc2ca57f00\r\nCorrelation ID: 5f5145bf-7114-4e6c-ab11-30e7ff84a056\r\nTimestamp: 2020-05-06 08:08:48Z",
    "error_codes": [
        28000
    ],
    "timestamp": "2020-05-06 08:08:48Z",
    "trace_id": "c3282396-6231-4e11-8300-77bc2ca57f00",
    "correlation_id": "5f5145bf-7114-4e6c-ab11-30e7ff84a056"
}

并且在尝试所有范围都具有 Microsoft Graph 时(从 Azure 门户复制)

public static final List<String> SCOPES = Arrays.asList(
    "https%3A%2F%2Fgraph.microsoft.com%2Foffline_access",
    "https%3A%2F%2Fgraph.microsoft.com%2FUser.Read",
    "https%3A%2F%2Fgraph.microsoft.com%2FMail.ReadWrite",
    "https%3A%2F%2Fgraph.microsoft.com%2FIMAP.AccessAsUser.All",
    "https%3A%2F%2Fgraph.microsoft.com%2FSMTP.Send"
);

Return 以下令牌(没有刷新令牌,但已请求 offline_access)

{
    "token_type": "Bearer",
    "scope": "profile openid email https://graph.microsoft.com/IMAP.AccessAsUser.All https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/SMTP.Send https://graph.microsoft.com/User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1..."
}

没有成功:

A1 NO AUTHENTICATE failed.

因此,如果您没有为范围指定 Outlook url,则它可能被假定为不允许通过 IMAP 和 SMTP 进行授权的 Graph one。

更新 4:

通过在同意步骤中请求我需要的所有范围,然后获得第一个仅具有图形范围的访问令牌和第二个使用指定 Outlook 范围的刷新令牌端点的访问令牌 - 它有效。 使用刷新令牌方法获取第二个访问令牌,因为如果您尝试通过授权代码获取访问令牌,您将收到以下错误:

{
    "error": "invalid_grant",
    "error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.\r\nTrace ID: 09fc80f4-f5fd-4e52-938f-d56b71dd0900\r\nCorrelation ID: 4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44\r\nTimestamp: 2020-05-08 12:13:30Z",
    "error_codes": [
        54005
    ],
    "timestamp": "2020-05-08 12:13:30Z",
    "trace_id": "09fc80f4-f5fd-4e52-938f-d56b71dd0900",
    "correlation_id": "4f35e05c-23c8-4fdc-a5a7-2fcde5a73b44"
}

所以不,我需要使用两个单独的令牌,具体取决于我需要管理的资源。

更新 5:

如果它仍然不起作用 - 检查您的组织是否启用了安全默认值 - 他们禁用帐户的 POP/IMAP/SMTP 身份验证 - https://techcommunity.microsoft.com/t5/exchange-team-blog/announcing-oauth-2-0-support-for-imap-and-smtp-auth-protocols-in/bc-p/1544725/highlight/true#M28589

@ldniov,我找不到与我所做的有什么不同。 提供我在下面使用的命令以供参考。

/* Url where users would be redirected to give consent */
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=0c56e5c5-0a9e-4ddf-a931-54de274c2e03
&response_type=code
&redirect_uri=https%3A%2F%2Fimap2.mailboxsync.com%2Fredirect%2F
&response_mode=query
&scope=offline_access%20https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All%20https%3A%2F%2Foutlook.office365.com%2FSMTP.Send
&state=12345

/*After user provides consent, exchanging auth code for refresh and access token */
curl -XPOST https://login.microsoftonline.com/test.onmicrosoft.com/oauth2/v2.0/token -d "client_id=0c56e5c5-0a9e-4ddf-a931-54de274c2e03&scope=offline_access%20https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All%20https%3A%2F%2Foutlook.office365.com%2FSMTP.Send&code=OAQABAAIAAAAm-06blBE1TpVMil8KPQ41HA4-ey0WVgK6WhqDDWBLoHBXdigqd8S_gE-uJBqH8f3z5U61GGQ_c_uJ__1n2r_IqwzTwjkmrd_VumomR-DaTz6tk0YUD6MdD5wZFC6ZET9N6clCnjSPnsBJ0Ee95qrLywipGqp9NL3Puea8AWZr06ltVrruvMpS9JOawOMgBMtbuUQjT_-C8EFmCz7yS-Iv-VjJYwlZ0S5jKnmRv9Iku8xt42VNjNsrRUVUJpvjbvRJWrmX6GYCD82VlQPntlwcTABqTsn-oNlFmFtbuE9fggTdvmRjq4diEPlwFHp0Fhjzolsmodh8tSIj0z2jHZXWFw3nbetaz_n71NSVc2DfKsKlr4sl-Zyew2xexOOwoHIkI33HVI3Hl0W-93zRkWMh5QxyDnU1R8pLVCU0GF1COThUvj1qaTpUW26nOgWdG1q0hXbLyhHe0HaLCY-RA0yg2fe49jCHNhOFiimkOgLrLD1a_-ICLhlAYkRUbd-aXdpbYZNOphvhNDkMqNILwk9LOHW3Cbsk6YDi1bwBTB2XTOvjyzb4uLz0_1exGc0XyA7wrSHf5l97k66sHgN6gEBKq-fgAOIgPMKPpovZ1ZiplS8Cd7ifcFmPfnAL5_ZJbt_0SCltNTX8v_qJRedCk8lNIoz18104eOdOyPyjFixlVi0MVpSFBoR6gEydFqoAeiwgAA&state=12345&session_state=1fab1545-2dc5-4102-b145-6258ea1ce97e&state=12345&redirect_uri=https%3A%2F%2Fimap2.mailboxsync.com%2Fredirect%2F&client_secret=xxxx&grant_type=authorization_code"

/*Exchanging refresh token for new access token*/
curl -XPOST https://login.microsoftonline.com/test.onmicrosoft.com/oauth2/v2.0/token -d "client_id=0c56e5c5-0a9e-4ddf-a931-54de274c2e03&scope=offline_access%20https%3A%2F%2Foutlook.office365.com%2FIMAP.AccessAsUser.All%20https%3A%2F%2Foutlook.office365.com%2FSMTP.Send&refresh_token=OAQABAAAAAAAm-06blBE1TpVMil8KPQ41c8A8SyRZDLkMDX7Vm5ay9zjRE7DfM5Mwo26ooW2zeB6pgKGZr1KPKko7XMSHM8DJj71i8TnCOrg4doYCsuGKGCw5fC74KKtp2wLD7w1mJ4BQJqldj2-42VqN63x8U9wGibI_DqBTn2VxGxaHbtpIGtNwzR4xwQgDt9-BiotNIuYksxmF9ZCIr6X_uMLvI4DLsBXxe67YsSlvR9VrU8cH-xJddMGPaDyJisWDcR0uW0-yk0b24zYaj4G203ksEji5wiPbuT_PeBrjV5b638s26AX_nMfvXSAjJfq-jWHouynq-3VYZp63eJ2o36yQWDUUMAXZ6-OT2Kl9-n4Y2kVkGNdepp_RBBQ7BDceip7J2nf5tHQKDm4S3nPGkfUNIyzk3I5jurLm9tyK8bVHzSEMz8TSg5slj_6Vsk0Oa1BWwW4tgdwWjsUm344jTMpfhc9iGDbc98o_47v7BfnUYZCtWLFQQxd68i01JPZvcyEp4T8aE42rQVtR55DqN3_7NYfPQBzdK_qX1Ue4r7ptOs7BIrRQgvSvuTE--ATVYwqD6s_XEeBZnnX8x1_2-o0VOmnTP8_2FvhvhgCj93F7VK0yZ6PxrBaT9No5AyDVWkHmURxziLJWAl7qEaO0cLuKKWLew1zbzuld5ahhdmwFVYtFMEmOBNlikcP8-8WGgYcjIiw03975Vty4oxoYY4-DOvAWcupTn-E69VBSRFwfWo3y8M9XimKL7TyqoXKqQnMRnpqGezAtGnMWScKKVC179w5V5KVSxuQGeWqE-z6YfVT-16rEqBlkByyFrLyF3VvR5nYgAA&grant_type=refresh_token&client_secret=xxx"

IMAP 调试日志

A1 验证 XOAUTH2 dXNlcj11c2VyXz...

A1 OK AUTHENTICATE 已完成。

A2 能力

* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS 移动 ID UNSELECT CLIENTACCESSRULES CLIENTNETWORKPRESENCELOCATION BACKENDAUTHENTICATE CHILDREN IDLE NAMESPACE LITERAL+

A2 OK 功能已完成。

DEBUG IMAPS: AUTH: PLAIN

调试 IMAPS:AUTH:XOAUTH2

使用 XOAUTH2

连接到 user_1@test.onmicrosoft.com

IMAP、SMTP 范围是针对 Exchange 资源而不是 Graph。而 User.Read、Mail.ReadWrite 用于图形资源。

我们不支持为两种资源生成令牌。因此错误 "Provided value for the input parameter scope is not valid because it contains more than one resource."

您应该通过两次调用 /token 分别生成两个令牌。 1. 一个为 Exchange 资源生成的 IMAP、SMTP 范围。 2. 另一个具有图形范围(User.Read、Mail.ReadWrite)的图形资源。

javax.mail example 使用 XOAUTH 和 O365 SMTP 发送电子邮件

我只询问发送电子邮件所需的那些范围...(不使用 Graph)。 可能我配置了一些不需要的权限。

其他回复已经指出:尽管您可以在 /authorize 端点同时授权不相关的范围,但对 /token 端点的每次调用可能只涉及相关范围的一个子集。

这个问题和几个回复还提出了以下问题:IMAP/POP/SMTP 的范围是否应该以 https://graph.microsoft.com/https://outlook.office365.com/ 为前缀,还是什么?事实上,Microsoft documents 范围名称应该以 https://outlook.office.com/:

为前缀
Protocol  Permission scope string
--------  -----------------------
IMAP      https://outlook.office.com/IMAP.AccessAsUser.All
POP       https://outlook.office.com/POP.AccessAsUser.All
SMTP      https://outlook.office.com/SMTP.Send