diff --git a/admin/oauth2callback.php b/admin/oauth2callback.php index c0b5572faca..f108eec8912 100644 --- a/admin/oauth2callback.php +++ b/admin/oauth2callback.php @@ -30,25 +30,36 @@ require_once(__DIR__ . '/../config.php'); +// The state parameter we've given (used in moodle as a redirect url). +// Per https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1, state is required, even during error responses. +$state = required_param('state', PARAM_LOCALURL); +$redirecturl = new moodle_url($state); +$params = $redirecturl->params(); + $error = optional_param('error', '', PARAM_RAW); + if ($error) { - $message = optional_param('error_description', '', PARAM_RAW); - if ($message) { - $SESSION->loginerrormsg = $message; - redirect(new moodle_url(get_login_url())); - } else { - $SESSION->loginerrormsg = $error; - redirect(new moodle_url(get_login_url())); + $message = optional_param('error_description', null, PARAM_RAW); + + // Errors can occur for authenticated users, such as when a user denies authorization for some internal service call. + // In such cases, propagate the error to the component redirect URI. + if (isloggedin()) { + if (isset($params['sesskey']) && confirm_sesskey($params['sesskey'])) { + $redirecturl->param('error', $error); + if ($message) { + $redirecturl->param('error_description', $message); + } + redirect($redirecturl); + } } + + // Not logged in or the sesskey verification failed, redirect to login + show errors. + $SESSION->loginerrormsg = $message ?? $error; + redirect(new moodle_url(get_login_url())); } // The authorization code generated by the authorization server. $code = required_param('code', PARAM_RAW); -// The state parameter we've given (used in moodle as a redirect url). -$state = required_param('state', PARAM_LOCALURL); - -$redirecturl = new moodle_url($state); -$params = $redirecturl->params(); if (isset($params['sesskey']) and confirm_sesskey($params['sesskey'])) { $redirecturl->param('oauth2code', $code);