mirror of
https://github.com/itflow-org/itflow
synced 2026-12-05 10:39:00 +00:00
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:
@@ -18,8 +18,10 @@ $error_description = escapeSql($_GET['error_description'] ?? '');
|
||||
|
||||
$session_state = $_SESSION['mail_oauth_state'] ?? '';
|
||||
$session_state_expires = intval($_SESSION['mail_oauth_state_expires_at'] ?? 0);
|
||||
// Graph's permissions or Exchange's - what Connect asked Microsoft for (functions/mail_graph.php)
|
||||
$way = ($_SESSION['mail_oauth_way'] ?? '') === 'graph' ? 'graph' : 'exchange';
|
||||
|
||||
unset($_SESSION['mail_oauth_state'], $_SESSION['mail_oauth_state_expires_at']);
|
||||
unset($_SESSION['mail_oauth_state'], $_SESSION['mail_oauth_state_expires_at'], $_SESSION['mail_oauth_way']);
|
||||
|
||||
if (!empty($error)) {
|
||||
$msg = "Microsoft OAuth authorization failed: $error";
|
||||
@@ -48,56 +50,44 @@ if (defined('BASE_URL') && !empty(BASE_URL)) {
|
||||
}
|
||||
|
||||
$redirect_uri = $base_url . '/admin/oauth_microsoft_mail_callback.php';
|
||||
$token_url = 'https://login.microsoftonline.com/' . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/token';
|
||||
$scope = 'offline_access openid profile https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send';
|
||||
|
||||
$ch = curl_init($token_url);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
|
||||
// Redeemed for what was asked for - a sign-in to one API at a time
|
||||
$response = mailGraphHttp('POST', MAIL_MICROSOFT_LOGIN_URL . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/token', [], [
|
||||
'client_id' => $config_mail_oauth_client_id,
|
||||
'client_secret' => $config_mail_oauth_client_secret,
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $code,
|
||||
'redirect_uri' => $redirect_uri,
|
||||
'scope' => $scope,
|
||||
], '', '&'));
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
|
||||
'scope' => mailMicrosoftConnectScope($way),
|
||||
], 20);
|
||||
|
||||
$raw_body = curl_exec($ch);
|
||||
$curl_err = curl_error($ch);
|
||||
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($raw_body === false || $http_code < 200 || $http_code >= 300) {
|
||||
$reason = !empty($curl_err) ? $curl_err : "HTTP $http_code";
|
||||
flashAlert("Microsoft OAuth token exchange failed: $reason", 'error');
|
||||
redirect($settings_mail_path);
|
||||
}
|
||||
|
||||
$json = json_decode($raw_body, true);
|
||||
if (!is_array($json) || empty($json['refresh_token']) || empty($json['access_token'])) {
|
||||
flashAlert("Microsoft OAuth token exchange failed: refresh token or access token missing.", 'error');
|
||||
$json = $response['json'];
|
||||
if (empty($json['refresh_token']) || empty($json['access_token'])) {
|
||||
flashAlert(escapeHtml($response['status'] >= 200 && $response['status'] < 300
|
||||
? 'Microsoft OAuth token exchange failed: refresh token or access token missing.'
|
||||
: mailGraphError($response, 'Microsoft OAuth token exchange')), 'error');
|
||||
redirect($settings_mail_path);
|
||||
}
|
||||
|
||||
$refresh_token = (string) $json['refresh_token'];
|
||||
$access_token = (string) $json['access_token'];
|
||||
$expires_at = date('Y-m-d H:i:s', time() + intval($json['expires_in'] ?? 3600));
|
||||
|
||||
$expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at);
|
||||
// An SMTP and IMAP sign-in is kept as what they sign in with - a Graph one isn't theirs, so they get their own when needed
|
||||
$access_token = $way === 'exchange' ? (string) $json['access_token'] : '';
|
||||
$expires_at_sql = $way === 'exchange' ? "'" . date('Y-m-d H:i:s', time() + intval($json['expires_in'] ?? 3600)) . "'" : 'NULL';
|
||||
|
||||
// Only the token - Sending and Receiving stay as they were set; connecting for one doesn't turn on the other. Sealed (functions/mail_secret.php)
|
||||
mysqli_query($mysqli, "UPDATE settings SET
|
||||
" . mailSecretSql('config_mail_oauth_refresh_token', $refresh_token) . ",
|
||||
" . mailSecretSql('config_mail_oauth_access_token', $access_token) . ",
|
||||
config_mail_oauth_access_token_expires_at = '$expires_at_esc'
|
||||
config_mail_oauth_access_token_expires_at = $expires_at_sql
|
||||
WHERE company_id = 1
|
||||
");
|
||||
|
||||
// What Microsoft Graph can do is asked afresh with the new sign-in (functions/mail_graph.php)
|
||||
// What Microsoft Graph can do is asked afresh with the new sign-in, and SMTP and IMAP for the rest (functions/mail_graph.php)
|
||||
mailGraphForget();
|
||||
$check = mailMicrosoftCheck($config_smtp_provider === 'microsoft_oauth', $config_imap_provider === 'microsoft_oauth', false);
|
||||
|
||||
logAudit("Settings", "Edit", "$session_name connected Microsoft 365 for mail");
|
||||
flashAlert("Microsoft 365 connected - ITFlow can now use the mailbox");
|
||||
logAudit("Settings", "Edit", "$session_name connected Microsoft 365 for mail" . ($way === 'graph' ? ' through Microsoft Graph' : ' by SMTP and IMAP'));
|
||||
flashAlert($check['ok']
|
||||
? 'Microsoft 365 connected. ' . escapeHtml($check['message'])
|
||||
: '<strong>Microsoft 365 is connected, but email can\'t go yet:</strong> ' . escapeHtml($check['message']), $check['ok'] ? 'success' : 'warning');
|
||||
redirect($settings_mail_path);
|
||||
|
||||
@@ -62,7 +62,8 @@ if (isset($_POST['edit_mail_smtp_settings']) || isset($_POST['edit_mail_imap_set
|
||||
* while Microsoft isn't picked), and the refresh token. No ID forgets the app:
|
||||
* its secret and token go too. A changed app or token makes what ITFlow last
|
||||
* signed in with useless, so that is fetched afresh when next needed.
|
||||
* Connect Microsoft 365 saves the same way, then goes to Microsoft to sign in.
|
||||
* Connect Microsoft 365 saves the same way, then goes to Microsoft to sign in,
|
||||
* asking for the permissions The app has says it was given (functions/mail_graph.php).
|
||||
*/
|
||||
if (isset($_POST['edit_mail_oauth_settings']) || isset($_POST['oauth_connect_microsoft_mail'])) {
|
||||
|
||||
@@ -157,10 +158,14 @@ if (isset($_POST['edit_mail_oauth_settings']) || isset($_POST['oauth_connect_mic
|
||||
$state = sha1(uniqid((string) mt_rand(), true));
|
||||
}
|
||||
|
||||
// Graph's permissions or Exchange's, as the app was given - the callback redeems the sign-in for the same
|
||||
$way = ($_POST['oauth_connect_way'] ?? '') === 'exchange' ? 'exchange' : 'graph';
|
||||
|
||||
$_SESSION['mail_oauth_state'] = $state;
|
||||
$_SESSION['mail_oauth_state_expires_at'] = time() + 600;
|
||||
$_SESSION['mail_oauth_way'] = $way;
|
||||
|
||||
$scope = 'offline_access openid profile https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send';
|
||||
$scope = mailMicrosoftConnectScope($way);
|
||||
|
||||
$authorize_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/authorize?'
|
||||
. http_build_query([
|
||||
@@ -170,10 +175,11 @@ if (isset($_POST['edit_mail_oauth_settings']) || isset($_POST['oauth_connect_mic
|
||||
'response_mode' => 'query',
|
||||
'scope' => $scope,
|
||||
'state' => $state,
|
||||
'prompt' => 'consent',
|
||||
// Which account to sign in as - not the consent screen, which a mailbox that may not approve apps can't get past even when an admin has
|
||||
'prompt' => 'select_account',
|
||||
], '', '&', PHP_QUERY_RFC3986);
|
||||
|
||||
logAudit("Settings", "Edit", "$session_name started connecting Microsoft 365 for mail");
|
||||
logAudit("Settings", "Edit", "$session_name started connecting Microsoft 365 for mail" . ($way === 'graph' ? ' through Microsoft Graph' : ' by SMTP and IMAP'));
|
||||
|
||||
redirect($authorize_url);
|
||||
}
|
||||
@@ -473,17 +479,22 @@ if (isset($_POST['test_oauth_token_refresh'])) {
|
||||
redirect($mail_tab_redirect);
|
||||
}
|
||||
|
||||
$token_url = 'https://oauth2.googleapis.com/token';
|
||||
// Microsoft 365: through Graph for what the app has its permission for, SMTP and IMAP only for the rest (functions/mail_graph.php)
|
||||
if ($provider === 'microsoft_oauth') {
|
||||
$token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($oauth_tenant_id) . "/oauth2/v2.0/token";
|
||||
$check = mailMicrosoftCheck($config_smtp_provider === 'microsoft_oauth', $config_imap_provider === 'microsoft_oauth');
|
||||
logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for Microsoft 365 mail settings");
|
||||
flashAlert(($check['ok'] ? 'OAuth token refresh successful for Microsoft 365. ' : '<strong>OAuth token test failed:</strong> ') . escapeHtml($check['message']), $check['ok'] ? 'success' : 'error');
|
||||
redirect($mail_tab_redirect);
|
||||
}
|
||||
|
||||
$token_url = 'https://oauth2.googleapis.com/token';
|
||||
|
||||
$post_fields = http_build_query([
|
||||
'client_id' => $oauth_client_id,
|
||||
'client_secret' => $oauth_client_secret,
|
||||
'refresh_token' => $oauth_refresh_token,
|
||||
'grant_type' => 'refresh_token',
|
||||
] + ($provider === 'microsoft_oauth' ? ['scope' => MAIL_MICROSOFT_EXCHANGE_SCOPE] : []));
|
||||
]);
|
||||
|
||||
$ch = curl_init($token_url);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
@@ -520,21 +531,8 @@ if (isset($_POST['test_oauth_token_refresh'])) {
|
||||
|
||||
mysqli_query($mysqli, "UPDATE settings SET " . mailSecretSql('config_mail_oauth_access_token', $new_access_token) . ", config_mail_oauth_access_token_expires_at = '$new_expires_at_esc'$refresh_sql WHERE company_id = 1");
|
||||
|
||||
$provider_label = $provider === 'microsoft_oauth' ? 'Microsoft 365' : 'Google Workspace';
|
||||
logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for $provider_label mail settings");
|
||||
logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for Google Workspace mail settings");
|
||||
|
||||
// And what Microsoft Graph can do for the mailbox now - asked afresh (functions/mail_graph.php)
|
||||
$graph_said = '';
|
||||
if ($provider === 'microsoft_oauth') {
|
||||
try {
|
||||
$graph_send = mailGraphToken('Mail.Send', true) !== null;
|
||||
$graph_read = mailGraphToken('Mail.ReadWrite') !== null;
|
||||
$graph_said = ' ' . mailGraphSays($config_smtp_provider === 'microsoft_oauth', $config_imap_provider === 'microsoft_oauth', $graph_send, $graph_read);
|
||||
} catch (\Throwable $e) {
|
||||
$graph_said = ' ' . escapeHtml($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
flashAlert("OAuth token refresh successful for $provider_label. Access token expires at $new_expires_at." . $graph_said);
|
||||
flashAlert("OAuth token refresh successful for Google Workspace. Access token expires at $new_expires_at.");
|
||||
redirect($mail_tab_redirect);
|
||||
}
|
||||
|
||||
@@ -331,6 +331,13 @@ if (!$config_module_enable_ticketing) {
|
||||
<button type="button" class="btn btn-outline-secondary clipboardjs" data-clipboard-target="#mailOauthRedirect" title="Copy"><i class="far fa-fw fa-copy"></i></button>
|
||||
</div>
|
||||
<div class="form-text">Under Authentication in the app registration, as a Web platform.</div>
|
||||
<div class="mt-3">
|
||||
<?= settingsSelect('oauth_connect_way', mailMicrosoftConnectWay($oauth_connected), [
|
||||
'graph' => 'Microsoft Graph\'s Mail.Send and Mail.ReadWrite',
|
||||
'exchange' => 'Exchange\'s SMTP.Send and IMAP.AccessAsUser.All',
|
||||
], ['id' => 'oauthConnectWay', 'icon' => 'fa-shield-alt', 'label' => 'The app has', 'data' => ['settings-untracked' => '1'],
|
||||
'help' => 'The permissions you gave it in Microsoft Entra - Connect asks Microsoft for just those, so there\'s nothing new to approve.']) ?>
|
||||
</div>
|
||||
<button type="submit" name="oauth_connect_microsoft_mail" class="btn btn-outline-primary mt-3">
|
||||
<i class="fab fa-fw fa-microsoft me-2"></i>Connect Microsoft 365
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user