- Вошел на сайт entra.micorosft.com и зарегистрировал приложение. Я создал секрет клиента для приложения.
- В зарегистрированном приложении я предоставил ему разрешение SMTP.Send.
- Я обновил мое Java-приложение следующим образом:
String authority = "https://login.microsoftonline.com/" + myTenantId;
String applicationIDURI = myApplicationIDURI (from the Entra UI);
Set scope = new HashSet();
scope.add(applicationIDURI + "/.default");
IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
ConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplication.builder(clientID, credential)
.authority(authority)
.build();
ClientCredentialParameters parameters = ClientCredentialParameters.builder(scope)
.build();
IAuthenticationResult result = confidentialClientApplication.acquireToken(parameters)
.join();
String oauthToken = result.accessToken();
/* Can print out this token - it looks reasonable */
Properties properties = new Properties();
properties.put("mail.debug.auth", "true");
properties.put("mail.debug", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.auth.login.disable", "true");
properties.put("mail.smtp.auth.mechanisms", "XOAUTH2");
properties.put("mail.smtp.auth.plain.disable", "true");
properties.put("mail.smtp.auth.xoauth2.disable", "false");
properties.put("mail.smtp.host", "smtp.office365.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.sasl.enable", "true");
// properties.put("mail.smtp.sasl.mechanisms.oauth2.oauthToken", encodedOauthToken);
// System.out.println("using encoded oauthToken");
properties.put("mail.smtp.sasl.mechanisms.oauth2.oauthToken", oauthToken);
System.out.println("using unencoded oauthToken");
properties.put("mail.smtp.ssl.protocols", "TLSv1.1 TLSv1.2");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.starttls.required", "true");
properties.put("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(properties,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, oauthToken);
}
}
);
Message message = new MimeMessage(session);
/* Set content and recipients in message */
Transport.send(message);
Когда этот код выполняется, я вижу, что токен доступа генерируется, как и ожидалось, и устанавливается соединение с SMTP-сервером. Однако при вызове Transport.send(message) выдается исключение (см. ниже). Я предполагаю, что либо зарегистрированное приложение неправильно сконфигурировано, либо приведенный выше код неправильно настраивает клиент, но я не могу понять, в чем проблема, и перепробовал много разных комбинаций вещей!
Спасибо. за любую помощь! Мартин
STARTTLS
220 2.0.0 SMTP server ready
EHLO host.docker.internal
250-BY3PR05CA0058.outlook.office365.com Hello [99.47.70.212]
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=myUsername@outlook.com, password=
DEBUG SMTP: Authenticate with SASL
DEBUG SMTP: SASL Mechanisms:
DEBUG SMTP: LOGIN
DEBUG SMTP: XOAUTH2
DEBUG SMTP:
DEBUG SMTP: SASL client XOAUTH2
DEBUG SMTP: SASL callback length: 2
DEBUG SMTP: SASL callback 0: javax.security.auth.callback.NameCallback@53fdffa1
DEBUG SMTP: SASL callback 1: javax.security.auth.callback.PasswordCallback@5562c41e
AUTH XOAUTH2
535 5.7.3 Authentication unsuccessful [BY3PR05CA0058.namprd05.prod.outlook.com 2024-10-13T16:17:32.016Z 08DCEB390DE37C0D]
DEBUG SMTP: SASL authentication failed
jakarta.mail.AuthenticationFailedException: failed to connect
at jakarta.mail.Service.connect(Service.java:379)
at jakarta.mail.Service.connect(Service.java:222)
at jakarta.mail.Service.connect(Service.java:171)
at jakarta.mail.Transport.send0(Transport.java:230)
at jakarta.mail.Transport.send(Transport.java:100)
Подробнее здесь: https://stackoverflow.com/questions/790 ... and-masl4j
Мобильная версия