diff --git a/course/loginas.php b/course/loginas.php
index 9feeec58e0519..d5db319229635 100644
--- a/course/loginas.php
+++ b/course/loginas.php
@@ -79,6 +79,9 @@
// Login as this user and return to course home page.
\core\session\manager::loginas($userid, $context);
+// Add a notification to let the logged in as user know that all content will be force cleaned
+// while in this session.
+\core\notification::info(get_string('sessionforceclean', 'core'));
$newfullname = fullname($USER, true);
$strloginas = get_string('loginas');
diff --git a/lang/en/moodle.php b/lang/en/moodle.php
index 7a93fd462c2ac..85815cda6607d 100644
--- a/lang/en/moodle.php
+++ b/lang/en/moodle.php
@@ -1808,6 +1808,7 @@
$string['separateandconnectedinfo'] = 'The scale based on the theory of separate and connected knowing. This theory describes two different ways that we can evaluate and learn about the things we see and hear.
- Separate knowers remain as objective as possible without including feelings and emotions. In a discussion with other people, they like to defend their own ideas, using logic to find holes in opponent\'s ideas.
- Connected knowers are more sensitive to other people. They are skilled at empathy and tend to listen and ask questions until they feel they can connect and "understand things from their point of view". They learn by trying to share the experiences that led to the knowledge they find in other people.
';
$string['servererror'] = 'An error occurred whilst communicating with the server';
$string['serverlocaltime'] = 'Server\'s local time';
+$string['sessionforceclean'] = 'As a security precaution, user generated scripts have been disabled within this session';
$string['setcategorytheme'] = 'Set category theme';
$string['setpassword'] = 'Set password';
$string['setpasswordinstructions'] = 'Please enter your new password below, then save changes.';
diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index 3c44836fb0b93..7e5de336a8686 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -2757,6 +2757,13 @@ function require_login($courseorid = null, $autologinguest = true, $cm = null, $
// Make sure the USER has a sesskey set up. Used for CSRF protection.
sesskey();
+ if (\core\session\manager::is_loggedinas()) {
+ // During a "logged in as" session we should force all content to be cleaned because the
+ // logged in user will be viewing potentially malicious user generated content.
+ // See MDL-63786 for more details.
+ $CFG->forceclean = true;
+ }
+
// Do not bother admins with any formalities, except for activities pending deletion.
if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
// Set the global $COURSE.