Microsoft 365 mail connects with the permissions the app has: The app has on the OAuth tab picks Microsoft Graph (graph.microsoft.com/.default) or Exchange's IMAP and SMTP scopes, Connect asks for the account instead of forcing the consent screen, the callback redeems for the same and keeps only an Exchange token as the SMTP/IMAP sign-in, and Connect's return and Test OAuth Token Refresh check Graph first and SMTP/IMAP only for what Graph lacks; 26.12.6 changelog

This commit is contained in:
johnnyq
2026-12-04 12:31:41 -05:00
parent b2d8863607
commit 80e6b724bb
6 changed files with 154 additions and 55 deletions

View File

@@ -20,6 +20,14 @@
* Microsoft hands back. An app that can't use Graph is asked again an hour
* later - or straight away after the OAuth tab is saved or connected
* (mailGraphForget()), or the sign-in is tested.
*
* Connect Microsoft 365 asks Microsoft for the permissions the app was given -
* Graph's, as https://graph.microsoft.com/.default (exactly what it was granted,
* so nothing new for anyone to approve), or Exchange's - and doesn't force the
* consent screen, which a mailbox that may not approve apps can't get past even
* once an admin has (mailMicrosoftConnectScope()). Coming back, and on Test OAuth
* Token Refresh, mailMicrosoftCheck() signs in through Graph first, and to SMTP
* and IMAP only for what Graph hasn't the permission for.
*/
defined('MAIL_GRAPH_URL') || define('MAIL_GRAPH_URL', 'https://graph.microsoft.com/v1.0');
@@ -137,6 +145,98 @@ function mailGraphToken($permission, $fresh = false) {
return in_array($permission, mailGraphScopesOf($scope), true) ? $token : null;
}
/* What Connect Microsoft 365 asks Microsoft for - $way 'graph' or 'exchange', the permissions the app was given */
function mailMicrosoftConnectScope($way) {
return 'openid profile ' . ($way === 'graph' ? MAIL_GRAPH_SCOPE : MAIL_MICROSOFT_EXCHANGE_SCOPE);
}
/* Which permissions the OAuth tab takes the app to have - Graph's for a mailbox not connected yet, then Graph's when Graph last said it has one of its mail permissions */
function mailMicrosoftConnectWay($connected) {
if (!$connected) {
return 'graph';
}
$state = mailGraphState();
return $state && ($state['send'] || $state['read']) ? 'graph' : 'exchange';
}
/*
* The SMTP and IMAP (Exchange) sign-in from the mailbox's refresh token - the one
* saved while it's good, unless $fresh - kept as what XOAUTH2 signs in with.
* ['ok', 'expires_at', 'error'].
*/
function mailMicrosoftExchangeToken($fresh = false) {
global $mysqli;
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_mail_oauth_client_id, config_mail_oauth_client_secret, config_mail_oauth_tenant_id,
config_mail_oauth_refresh_token, config_mail_oauth_access_token, config_mail_oauth_access_token_expires_at FROM settings WHERE company_id = 1"));
$client_id = trim((string) ($row['config_mail_oauth_client_id'] ?? ''));
$secret = trim(mailSecretOpen($row['config_mail_oauth_client_secret'] ?? ''));
$tenant = trim((string) ($row['config_mail_oauth_tenant_id'] ?? ''));
$refresh_token = trim(mailSecretOpen($row['config_mail_oauth_refresh_token'] ?? ''));
if ($client_id === '' || $secret === '' || $tenant === '' || $refresh_token === '') {
return ['ok' => false, 'expires_at' => '', 'error' => 'The app\'s client ID, secret and tenant ID, and a connected mailbox, are needed first.'];
}
$expires = strtotime((string) ($row['config_mail_oauth_access_token_expires_at'] ?? ''));
if (!$fresh && $expires && $expires - 120 > time() && mailSecretOpen($row['config_mail_oauth_access_token'] ?? '') !== '') {
return ['ok' => true, 'expires_at' => date('Y-m-d H:i:s', $expires), 'error' => ''];
}
$response = mailGraphHttp('POST', MAIL_MICROSOFT_LOGIN_URL . rawurlencode($tenant) . '/oauth2/v2.0/token', [], [
'client_id' => $client_id,
'client_secret' => $secret,
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token,
'scope' => MAIL_MICROSOFT_EXCHANGE_SCOPE,
]);
$token = (string) ($response['json']['access_token'] ?? '');
if ($token === '') {
return ['ok' => false, 'expires_at' => '', 'error' => mailGraphError($response, 'Signing in to SMTP and IMAP as the mailbox')];
}
$expires_at = date('Y-m-d H:i:s', time() + max(300, intval($response['json']['expires_in'] ?? 3600)));
$set = mailSecretSql('config_mail_oauth_access_token', $token) . ", config_mail_oauth_access_token_expires_at = '$expires_at'";
if (!empty($response['json']['refresh_token'])) {
$set .= ', ' . mailSecretSql('config_mail_oauth_refresh_token', (string) $response['json']['refresh_token']);
}
mysqli_query($mysqli, "UPDATE settings SET $set WHERE company_id = 1");
return ['ok' => true, 'expires_at' => $expires_at, 'error' => ''];
}
/*
* Whether Microsoft 365 mail can sign in now, asked afresh - for each side on
* Microsoft 365 ($send_ms, $read_ms), through Graph where the app has its
* permission and by SMTP or IMAP for the rest, so an app with Graph's
* permissions only isn't failed for lacking Exchange's. $fresh_exchange: an
* SMTP and IMAP sign-in saved a moment ago (Connect's) does. ['ok', 'message'],
* the message as plain text.
*/
function mailMicrosoftCheck($send_ms, $read_ms, $fresh_exchange = true) {
$graph_send = $graph_read = false;
$graph_error = '';
try {
$graph_send = mailGraphToken('Mail.Send', true) !== null;
$graph_read = mailGraphToken('Mail.ReadWrite') !== null;
} catch (\Throwable $e) {
$graph_error = $e->getMessage();
}
$said = mailGraphSays($send_ms, $read_ms, $graph_send, $graph_read);
if ($graph_error !== '') {
return ['ok' => false, 'message' => $graph_error];
}
$need = array_filter(['SMTP' => $send_ms && !$graph_send, 'IMAP' => $read_ms && !$graph_read]);
if (!$need) {
return ['ok' => true, 'message' => "Signed in to Microsoft Graph as the mailbox. $said"];
}
$exchange = mailMicrosoftExchangeToken($fresh_exchange);
if (!$exchange['ok']) {
$missing = array_keys(array_filter(['Mail.Send' => isset($need['SMTP']), 'Mail.ReadWrite' => isset($need['IMAP'])]));
$exchange_names = array_keys(array_filter(['SMTP.Send' => isset($need['SMTP']), 'IMAP.AccessAsUser.All' => isset($need['IMAP'])]));
return ['ok' => false, 'message' => $exchange['error'] . ' The app needs Microsoft Graph\'s ' . implode(' and ', $missing) . ' - or Exchange\'s '
. implode(' and ', $exchange_names) . ' - with admin consent, then connect the mailbox again.'];
}
return ['ok' => true, 'message' => 'Signed in to ' . implode(' and ', array_keys($need)) . ' as the mailbox, good until '
. date('g:i A', strtotime($exchange['expires_at'])) . ". $said"];
}
/* Forget what Graph last said, so it is asked again when next needed - the app or its sign-in changed */
function mailGraphForget() {
global $mysqli;