diff --git a/lib/SimpleSAML/Auth/AuthenticationFactory.php b/lib/SimpleSAML/Auth/AuthenticationFactory.php
index 7335bc2d5643ba76e6d76c5a524ce9af444fe53c..25dc18307d22f0494d4bf7b527e88aafab6eb34e 100644
--- a/lib/SimpleSAML/Auth/AuthenticationFactory.php
+++ b/lib/SimpleSAML/Auth/AuthenticationFactory.php
@@ -2,12 +2,14 @@
 
 namespace SimpleSAML\Auth;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Session;
+
 /**
  * Factory class to get instances of \SimpleSAML\Auth\Simple for a given authentication source.
  */
 class AuthenticationFactory
 {
-
     /** @var \SimpleSAML\Configuration */
     protected $config;
 
@@ -15,7 +17,7 @@ class AuthenticationFactory
     protected $session;
 
 
-    public function __construct(\SimpleSAML\Configuration $config, \SimpleSAML\Session $session)
+    public function __construct(Configuration $config, Session $session)
     {
         $this->config = $config;
         $this->session = $session;
@@ -34,4 +36,4 @@ class AuthenticationFactory
     {
         return new Simple($as, $this->config, $this->session);
     }
-}
\ No newline at end of file
+}
diff --git a/lib/SimpleSAML/Auth/Default.php b/lib/SimpleSAML/Auth/Default.php
index eb6ef0479d051bd68b9a34c14a789112c46e7ec6..7379c3d99312eca58403828cb2629ebbba2207f3 100644
--- a/lib/SimpleSAML/Auth/Default.php
+++ b/lib/SimpleSAML/Auth/Default.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Auth;
 
+use SimpleSAML\Module\saml\Auth\Source\SP;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+
 /**
  * Implements the default behaviour for authentication.
  *
@@ -70,7 +74,7 @@ class DefaultAuth
         assert(is_string($returnURL));
         assert(is_string($authority));
 
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
 
         $state = $session->getAuthData($authority, 'LogoutState');
         $session->doLogout($authority);
@@ -101,7 +105,7 @@ class DefaultAuth
 
         self::initLogoutReturn($returnURL, $authority);
 
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnURL);
+        Utils\HTTP::redirectTrustedURL($returnURL);
     }
 
 
@@ -115,7 +119,7 @@ class DefaultAuth
         assert(is_array($state));
         assert(array_key_exists('\SimpleSAML\Auth\DefaultAuth.ReturnURL', $state));
 
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($state['\SimpleSAML\Auth\DefaultAuth.ReturnURL']);
+        Utils\HTTP::redirectTrustedURL($state['\SimpleSAML\Auth\DefaultAuth.ReturnURL']);
     }
 
 
@@ -140,7 +144,7 @@ class DefaultAuth
      */
     public static function handleUnsolicitedAuth($authId, array $state, $redirectTo)
     {
-        \SimpleSAML\Module\saml\Auth\Source\SP::handleUnsolicitedAuth($authId, $state, $redirectTo);
+        SP::handleUnsolicitedAuth($authId, $state, $redirectTo);
     }
 
 
diff --git a/lib/SimpleSAML/Auth/ProcessingChain.php b/lib/SimpleSAML/Auth/ProcessingChain.php
index e2ba6aa07cdff4af663eeb45628669919f1d1988..e07fc25349caf30bd9bab665305bf2db8a54985a 100644
--- a/lib/SimpleSAML/Auth/ProcessingChain.php
+++ b/lib/SimpleSAML/Auth/ProcessingChain.php
@@ -2,6 +2,12 @@
 
 namespace SimpleSAML\Auth;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
 /**
  * Class for implementing authentication processing chains for IdPs.
  *
@@ -55,7 +61,7 @@ class ProcessingChain
 
         $this->filters = [];
 
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $configauthproc = $config->getArray('authproc.'.$mode, null);
 
         if (!empty($configauthproc)) {
@@ -73,7 +79,7 @@ class ProcessingChain
             self::addFilters($this->filters, $spFilters);
         }
 
-        \SimpleSAML\Logger::debug('Filter config for '.$idpMetadata['entityid'].'->'.
+        Logger::debug('Filter config for '.$idpMetadata['entityid'].'->'.
             $spMetadata['entityid'].': '.str_replace("\n", '', var_export($this->filters, true)));
     }
 
@@ -153,7 +159,7 @@ class ProcessingChain
             throw new \Exception('Authentication processing filter without name given.');
         }
 
-        $className = \SimpleSAML\Module::resolveClass(
+        $className = Module::resolveClass(
             $config['class'],
             'Auth\Process',
             '\SimpleSAML\Auth\ProcessingFilter'
@@ -206,7 +212,7 @@ class ProcessingChain
                 $filter = array_shift($state[self::FILTERS_INDEX]);
                 $filter->process($state);
             }
-        } catch (\SimpleSAML\Error\Exception $e) {
+        } catch (Error\Exception $e) {
             // No need to convert the exception
             throw $e;
         } catch (\Exception $e) {
@@ -214,7 +220,7 @@ class ProcessingChain
              * To be consistent with the exception we return after an redirect,
              * we convert this exception before returning it.
              */
-            throw new \SimpleSAML\Error\UnserializableException($e);
+            throw new Error\UnserializableException($e);
         }
 
         // Completed
@@ -241,10 +247,10 @@ class ProcessingChain
             $filter = array_shift($state[self::FILTERS_INDEX]);
             try {
                 $filter->process($state);
-            } catch (\SimpleSAML\Error\Exception $e) {
+            } catch (Error\Exception $e) {
                 State::throwException($state, $e);
             } catch (\Exception $e) {
-                $e = new \SimpleSAML\Error\UnserializableException($e);
+                $e = new Error\UnserializableException($e);
                 State::throwException($state, $e);
             }
         }
@@ -261,7 +267,7 @@ class ProcessingChain
              * in $state['ReturnURL'].
              */
             $id = State::saveState($state, self::COMPLETED_STAGE);
-            \SimpleSAML\Utils\HTTP::redirectTrustedURL($state['ReturnURL'], [self::AUTHPARAM => $id]);
+            Utils\HTTP::redirectTrustedURL($state['ReturnURL'], [self::AUTHPARAM => $id]);
         } else {
             /* Pass the state to the function defined in $state['ReturnCall']. */
 
@@ -309,10 +315,10 @@ class ProcessingChain
             $filter = array_shift($state[self::FILTERS_INDEX]);
             try {
                 $filter->process($state);
-            } catch (\SimpleSAML\Error\NoPassive $e) {
+            } catch (Error\NoPassive $e) {
                 // @deprecated will be removed in 2.0
                 // Ignore \SimpleSAML\Error\NoPassive exceptions
-            } catch (\SimpleSAML\Module\saml\Error\NoPassive $e) {
+            } catch (Module\saml\Error\NoPassive $e) {
                 // Ignore \SimpleSAML\Module\saml\Error\NoPassive exceptions
             }
         }
@@ -345,10 +351,10 @@ class ProcessingChain
 
         if (isset($state['Destination']['userid.attribute'])) {
             $attributeName = $state['Destination']['userid.attribute'];
-            \SimpleSAML\Logger::debug("The 'userid.attribute' option has been deprecated.");
+            Logger::debug("The 'userid.attribute' option has been deprecated.");
         } elseif (isset($state['Source']['userid.attribute'])) {
             $attributeName = $state['Source']['userid.attribute'];
-            \SimpleSAML\Logger::debug("The 'userid.attribute' option has been deprecated.");
+            Logger::debug("The 'userid.attribute' option has been deprecated.");
         } else {
             // Default attribute
             $attributeName = 'eduPersonPrincipalName';
@@ -360,12 +366,12 @@ class ProcessingChain
 
         $uid = $state['Attributes'][$attributeName];
         if (count($uid) === 0) {
-            \SimpleSAML\Logger::warning('Empty user id attribute ['.$attributeName.'].');
+            Logger::warning('Empty user id attribute ['.$attributeName.'].');
             return;
         }
 
         if (count($uid) > 1) {
-            \SimpleSAML\Logger::warning('Multiple attribute values for user id attribute ['.$attributeName.'].');
+            Logger::warning('Multiple attribute values for user id attribute ['.$attributeName.'].');
             return;
         }
 
@@ -373,7 +379,7 @@ class ProcessingChain
         $uid = $uid[0];
 
         if (empty($uid)) {
-            \SimpleSAML\Logger::warning('Empty value in attribute '.$attributeName.". on user. Cannot set UserID.");
+            Logger::warning('Empty value in attribute '.$attributeName.". on user. Cannot set UserID.");
             return;
         }
         $state['UserID'] = $uid;
diff --git a/lib/SimpleSAML/Auth/Simple.php b/lib/SimpleSAML/Auth/Simple.php
index 927418261878eb50ff2a0a0c96019a9da2f7913a..769c0ab55230ed6eadf7637aec97ae10ef03e1ef 100644
--- a/lib/SimpleSAML/Auth/Simple.php
+++ b/lib/SimpleSAML/Auth/Simple.php
@@ -3,10 +3,10 @@
 namespace SimpleSAML\Auth;
 
 use \SimpleSAML\Configuration;
-use \SimpleSAML\Error\AuthSource as AuthSourceError;
+use \SimpleSAML\Error;
 use \SimpleSAML\Module;
 use \SimpleSAML\Session;
-use \SimpleSAML\Utils\HTTP;
+use \SimpleSAML\Utils;
 
 /**
  * Helper class for simple authentication applications.
@@ -65,7 +65,7 @@ class Simple
     {
         $as = Source::getById($this->authSource);
         if ($as === null) {
-            throw new AuthSourceError($this->authSource, 'Unknown authentication source.');
+            throw new Error\AuthSource($this->authSource, 'Unknown authentication source.');
         }
         return $as;
     }
@@ -139,12 +139,12 @@ class Simple
             if (array_key_exists('ReturnCallback', $params)) {
                 $returnTo = (array) $params['ReturnCallback'];
             } else {
-                $returnTo = HTTP::getSelfURL();
+                $returnTo = Utils\HTTP::getSelfURL();
             }
         }
 
         if (is_string($returnTo) && $keepPost && $_SERVER['REQUEST_METHOD'] === 'POST') {
-            $returnTo = HTTP::getPOSTRedirectURL($returnTo, $_POST);
+            $returnTo = Utils\HTTP::getPOSTRedirectURL($returnTo, $_POST);
         }
 
         if (array_key_exists('ErrorURL', $params)) {
@@ -190,7 +190,7 @@ class Simple
         assert(is_array($params) || is_string($params) || $params === null);
 
         if ($params === null) {
-            $params = HTTP::getSelfURL();
+            $params = Utils\HTTP::getSelfURL();
         }
 
         if (is_string($params)) {
@@ -249,7 +249,7 @@ class Simple
                 $stateID = State::saveState($state, $state['ReturnStateStage']);
                 $params[$state['ReturnStateParam']] = $stateID;
             }
-            HTTP::redirectTrustedURL($state['ReturnTo'], $params);
+            Utils\HTTP::redirectTrustedURL($state['ReturnTo'], $params);
         }
     }
 
@@ -321,7 +321,7 @@ class Simple
         assert($returnTo === null || is_string($returnTo));
 
         if ($returnTo === null) {
-            $returnTo = HTTP::getSelfURL();
+            $returnTo = Utils\HTTP::getSelfURL();
         }
 
         $login = Module::getModuleURL('core/as_login.php', [
@@ -346,7 +346,7 @@ class Simple
         assert($returnTo === null || is_string($returnTo));
 
         if ($returnTo === null) {
-            $returnTo = HTTP::getSelfURL();
+            $returnTo = Utils\HTTP::getSelfURL();
         }
 
         $logout = Module::getModuleURL('core/as_logout.php', [
@@ -371,15 +371,15 @@ class Simple
     protected function getProcessedURL($url = null)
     {
         if ($url === null) {
-            $url = HTTP::getSelfURL();
+            $url = Utils\HTTP::getSelfURL();
         }
 
         $scheme = parse_url($url, PHP_URL_SCHEME);
-        $host = parse_url($url, PHP_URL_HOST) ? : HTTP::getSelfHost();
+        $host = parse_url($url, PHP_URL_HOST) ? : Utils\HTTP::getSelfHost();
         $port = parse_url($url, PHP_URL_PORT) ? : (
-            $scheme ? '' : trim(HTTP::getServerPort(), ':')
+            $scheme ? '' : trim(Utils\HTTP::getServerPort(), ':')
         );
-        $scheme = $scheme ? : (HTTP::getServerHTTPS() ? 'https' : 'http');
+        $scheme = $scheme ? : (Utils\HTTP::getServerHTTPS() ? 'https' : 'http');
         $path = parse_url($url, PHP_URL_PATH) ? : '/';
         $query = parse_url($url, PHP_URL_QUERY) ? : '';
         $fragment = parse_url($url, PHP_URL_FRAGMENT) ? : '';
diff --git a/lib/SimpleSAML/Auth/Source.php b/lib/SimpleSAML/Auth/Source.php
index 6bf02b352675e9bd26da3b8d47969e5f4980d47c..3327103d6fe11baf08d36b46be36924c73f2478c 100644
--- a/lib/SimpleSAML/Auth/Source.php
+++ b/lib/SimpleSAML/Auth/Source.php
@@ -2,6 +2,13 @@
 
 namespace SimpleSAML\Auth;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+
 /**
  * This class defines a base class for authentication source.
  *
@@ -53,7 +60,7 @@ abstract class Source
     {
         assert(is_string($type));
 
-        $config = \SimpleSAML\Configuration::getConfig('authsources.php');
+        $config = Configuration::getConfig('authsources.php');
 
         $ret = [];
 
@@ -117,7 +124,7 @@ abstract class Source
         assert(isset($state['ReturnCallback']));
 
         // the default implementation just copies over the previous authentication data
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $data = $session->getAuthState($this->authId);
         foreach ($data as $k => $v) {
             $state[$k] = $v;
@@ -195,10 +202,10 @@ abstract class Source
 
         try {
             $this->authenticate($state);
-        } catch (\SimpleSAML\Error\Exception $e) {
+        } catch (Error\Exception $e) {
             State::throwException($state, $e);
         } catch (\Exception $e) {
-            $e = new \SimpleSAML\Error\UnserializableException($e);
+            $e = new Error\UnserializableException($e);
             State::throwException($state, $e);
         }
         self::loginCompleted($state);
@@ -224,13 +231,13 @@ abstract class Source
         $return = $state['\SimpleSAML\Auth\Source.Return'];
 
         // save session state
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $authId = $state['\SimpleSAML\Auth\Source.id'];
         $session->doLogin($authId, State::getPersistentAuthData($state));
 
         if (is_string($return)) {
             // redirect...
-            \SimpleSAML\Utils\HTTP::redirectTrustedURL($return);
+            Utils\HTTP::redirectTrustedURL($return);
         } else {
             call_user_func($return, $state);
         }
@@ -311,7 +318,7 @@ abstract class Source
 
         try {
             // Check whether or not there's a factory responsible for instantiating our Auth Source instance
-            $factoryClass = \SimpleSAML\Module::resolveClass(
+            $factoryClass = Module::resolveClass(
                 $id,
                 'Auth\Source\Factory',
                 '\SimpleSAML\Auth\SourceFactory'
@@ -322,7 +329,7 @@ abstract class Source
             $authSource = $factory->create($info, $config);
         } catch (\Exception $e) {
             // If not, instantiate the Auth Source here
-            $className = \SimpleSAML\Module::resolveClass($id, 'Auth\Source', '\SimpleSAML\Auth\Source');
+            $className = Module::resolveClass($id, 'Auth\Source', '\SimpleSAML\Auth\Source');
             $authSource = new $className($info, $config);
         }
 
@@ -354,12 +361,12 @@ abstract class Source
         assert($type === null || is_string($type));
 
         // for now - load and parse config file
-        $config = \SimpleSAML\Configuration::getConfig('authsources.php');
+        $config = Configuration::getConfig('authsources.php');
 
         $authConfig = $config->getArray($authId, null);
         if ($authConfig === null) {
             if ($type !== null) {
-                throw new \SimpleSAML\Error\Exception(
+                throw new Error\Exception(
                     'No authentication source with id '.
                     var_export($authId, true).' found.'
                 );
@@ -374,7 +381,7 @@ abstract class Source
         }
 
         // the authentication source doesn't have the correct type
-        throw new \SimpleSAML\Error\Exception(
+        throw new Error\Exception(
             'Invalid type of authentication source '.
             var_export($authId, true).'. Was '.var_export(get_class($ret), true).
             ', should be '.var_export($type, true).'.'
@@ -395,9 +402,9 @@ abstract class Source
 
         $source = $state['\SimpleSAML\Auth\Source.logoutSource'];
 
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         if (!$session->isValid($source)) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Received logout from an invalid authentication source '.
                 var_export($source, true)
             );
@@ -445,12 +452,12 @@ abstract class Source
             'state'    => $callbackState,
         ];
 
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $session->setData(
             '\SimpleSAML\Auth\Source.LogoutCallbacks',
             $id,
             $data,
-            \SimpleSAML\Session::DATA_TIMEOUT_SESSION_END
+            Session::DATA_TIMEOUT_SESSION_END
         );
     }
 
@@ -472,7 +479,7 @@ abstract class Source
 
         $id = strlen($this->authId).':'.$this->authId.$assoc;
 
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
 
         $data = $session->getData('\SimpleSAML\Auth\Source.LogoutCallbacks', $id);
         if ($data === null) {
@@ -501,7 +508,7 @@ abstract class Source
      */
     public static function getSources()
     {
-        $config = \SimpleSAML\Configuration::getOptionalConfig('authsources.php');
+        $config = Configuration::getOptionalConfig('authsources.php');
 
         return $config->getOptions();
     }
diff --git a/lib/SimpleSAML/Auth/State.php b/lib/SimpleSAML/Auth/State.php
index 8c6019a6655c9bee9cda90c26d12486c598181f4..8e5030ddf825a3de6a7c31951a74ee5406022f06 100644
--- a/lib/SimpleSAML/Auth/State.php
+++ b/lib/SimpleSAML/Auth/State.php
@@ -2,6 +2,12 @@
 
 namespace SimpleSAML\Auth;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+
 /**
  * This is a helper class for saving and loading state information.
  *
@@ -151,7 +157,7 @@ class State
         assert(is_bool($rawId));
 
         if (!array_key_exists(self::ID, $state)) {
-            $state[self::ID] = \SimpleSAML\Utils\Random::generateID();
+            $state[self::ID] = Utils\Random::generateID();
         }
 
         $id = $state[self::ID];
@@ -174,7 +180,7 @@ class State
     private static function getStateTimeout()
     {
         if (self::$stateTimeout === null) {
-            $globalConfig = \SimpleSAML\Configuration::getInstance();
+            $globalConfig = Configuration::getInstance();
             self::$stateTimeout = $globalConfig->getInteger('session.state.timeout', 60 * 60);
         }
 
@@ -208,10 +214,10 @@ class State
 
         // Save state
         $serializedState = serialize($state);
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $session->setData('\SimpleSAML\Auth\State', $id, $serializedState, self::getStateTimeout());
 
-        \SimpleSAML\Logger::debug('Saved state: '.var_export($return, true));
+        Logger::debug('Saved state: '.var_export($return, true));
 
         return $return;
     }
@@ -234,9 +240,9 @@ class State
             $clonedState[self::CLONE_ORIGINAL_ID] = $state[self::ID];
             unset($clonedState[self::ID]);
 
-            \SimpleSAML\Logger::debug('Cloned state: '.var_export($state[self::ID], true));
+            Logger::debug('Cloned state: '.var_export($state[self::ID], true));
         } else {
-            \SimpleSAML\Logger::debug('Cloned state with undefined id.');
+            Logger::debug('Cloned state with undefined id.');
         }
 
         return $clonedState;
@@ -264,11 +270,11 @@ class State
         assert(is_string($id));
         assert(is_string($stage));
         assert(is_bool($allowMissing));
-        \SimpleSAML\Logger::debug('Loading state: '.var_export($id, true));
+        Logger::debug('Loading state: '.var_export($id, true));
 
         $sid = self::parseStateID($id);
 
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $state = $session->getData('\SimpleSAML\Auth\State', $sid['id']);
 
         if ($state === null) {
@@ -278,10 +284,10 @@ class State
             }
 
             if ($sid['url'] === null) {
-                throw new \SimpleSAML\Error\NoState();
+                throw new Error\NoState();
             }
 
-            \SimpleSAML\Utils\HTTP::redirectUntrustedURL($sid['url']);
+            Utils\HTTP::redirectUntrustedURL($sid['url']);
         }
 
         $state = unserialize($state);
@@ -299,13 +305,13 @@ class State
             $msg = 'Wrong stage in state. Was \''.$state[self::STAGE].
                 '\', should be \''.$stage.'\'.';
 
-            \SimpleSAML\Logger::warning($msg);
+            Logger::warning($msg);
 
             if ($sid['url'] === null) {
                 throw new \Exception($msg);
             }
 
-            \SimpleSAML\Utils\HTTP::redirectUntrustedURL($sid['url']);
+            Utils\HTTP::redirectUntrustedURL($sid['url']);
         }
 
         return $state;
@@ -329,9 +335,9 @@ class State
             return;
         }
 
-        \SimpleSAML\Logger::debug('Deleting state: '.var_export($state[self::ID], true));
+        Logger::debug('Deleting state: '.var_export($state[self::ID], true));
 
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $session->deleteData('\SimpleSAML\Auth\State', $state[self::ID]);
     }
 
@@ -345,7 +351,7 @@ class State
      * @throws \SimpleSAML\Error\Exception If there is no exception handler defined, it will just throw the $exception.
      * @return void
      */
-    public static function throwException($state, \SimpleSAML\Error\Exception $exception)
+    public static function throwException($state, Error\Exception $exception)
     {
         assert(is_array($state));
 
@@ -355,7 +361,7 @@ class State
             $id = self::saveState($state, self::EXCEPTION_STAGE);
 
             // Redirect to the exception handler
-            \SimpleSAML\Utils\HTTP::redirectTrustedURL(
+            Utils\HTTP::redirectTrustedURL(
                 $state[self::EXCEPTION_HANDLER_URL],
                 [self::EXCEPTION_PARAM => $id]
             );
diff --git a/lib/SimpleSAML/Auth/TimeLimitedToken.php b/lib/SimpleSAML/Auth/TimeLimitedToken.php
index 5b4c3c2a294aca514dc49c0cbc802a68429e6878..ec6ac4c2cf35277c1f1009528bb6b5a6f292225c 100644
--- a/lib/SimpleSAML/Auth/TimeLimitedToken.php
+++ b/lib/SimpleSAML/Auth/TimeLimitedToken.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Auth;
 
+use SimpleSAML\Utils;
+
 /**
  * A class that generates and verifies time-limited tokens.
  */
@@ -44,7 +46,7 @@ class TimeLimitedToken
     public function __construct($lifetime = 900, $secretSalt = null, $skew = 1, $algo = 'sha1')
     {
         if ($secretSalt === null) {
-            $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
+            $secretSalt = Utils\Config::getSecretSalt();
         }
 
         if (!in_array($algo, hash_algos(), true)) {
diff --git a/lib/SimpleSAML/Bindings/Shib13/Artifact.php b/lib/SimpleSAML/Bindings/Shib13/Artifact.php
index 30d7d130bf0d083388dbf9a16448ea61a2f5f13a..702c59f828455eaf67aa8d129d89356de5cf0f57 100644
--- a/lib/SimpleSAML/Bindings/Shib13/Artifact.php
+++ b/lib/SimpleSAML/Bindings/Shib13/Artifact.php
@@ -9,13 +9,9 @@
 namespace SimpleSAML\Bindings\Shib13;
 
 use SAML2\DOMDocumentFactory;
+use SimpleSAML\Configuration;
 use SimpleSAML\Error;
-use SimpleSAML\Utils\Config;
-use SimpleSAML\Utils\HTTP;
-use SimpleSAML\Utils\Random;
-use SimpleSAML\Utils\System;
-use SimpleSAML\Utils\Time;
-use SimpleSAML\Utils\XML;
+use SimpleSAML\Utils;
 
 class Artifact
 {
@@ -61,9 +57,9 @@ class Artifact
         $msg = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'.
             '<SOAP-ENV:Body>'.
             '<samlp:Request xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol"'.
-            ' RequestID="'.Random::generateID().'"'.
+            ' RequestID="'.Utils\Random::generateID().'"'.
             ' MajorVersion="1" MinorVersion="1"'.
-            ' IssueInstant="'.Time::generateTimestamp().'"'.
+            ' IssueInstant="'.Utils\Time::generateTimestamp().'"'.
             '>';
 
         foreach ($artifacts as $a) {
@@ -96,18 +92,18 @@ class Artifact
         }
 
         $soapEnvelope = $doc->firstChild;
-        if (!XML::isDOMNodeOfType($soapEnvelope, 'Envelope', 'http://schemas.xmlsoap.org/soap/envelope/')) {
+        if (!Utils\XML::isDOMNodeOfType($soapEnvelope, 'Envelope', 'http://schemas.xmlsoap.org/soap/envelope/')) {
             throw new Error\Exception('Expected artifact response to contain a <soap:Envelope> element.');
         }
 
-        $soapBody = XML::getDOMChildren($soapEnvelope, 'Body', 'http://schemas.xmlsoap.org/soap/envelope/');
+        $soapBody = Utils\XML::getDOMChildren($soapEnvelope, 'Body', 'http://schemas.xmlsoap.org/soap/envelope/');
         if (count($soapBody) === 0) {
             throw new Error\Exception('Couldn\'t find <soap:Body> in <soap:Envelope>.');
         }
         $soapBody = $soapBody[0];
 
 
-        $responseElement = XML::getDOMChildren($soapBody, 'Response', 'urn:oasis:names:tc:SAML:1.0:protocol');
+        $responseElement = Utils\XML::getDOMChildren($soapBody, 'Response', 'urn:oasis:names:tc:SAML:1.0:protocol');
         if (count($responseElement) === 0) {
             throw new Error\Exception('Couldn\'t find <saml1p:Response> in <soap:Body>.');
         }
@@ -133,12 +129,12 @@ class Artifact
      * @return string The <saml1p:Response> element, as an XML string.
      * @throws Error\Exception
      */
-    public static function receive(\SimpleSAML\Configuration $spMetadata, \SimpleSAML\Configuration $idpMetadata)
+    public static function receive(Configuration $spMetadata, Configuration $idpMetadata)
     {
         $artifacts = self::getArtifacts();
         $request = self::buildRequest($artifacts);
 
-        XML::debugSAMLMessage($request, 'out');
+        Utils\XML::debugSAMLMessage($request, 'out');
 
         $url = $idpMetadata->getDefaultEndpoint(
             'ArtifactResolutionService',
@@ -157,12 +153,12 @@ class Artifact
                 "-----END CERTIFICATE-----\n";
         }
 
-        $file = System::getTempDir().DIRECTORY_SEPARATOR.sha1($certData).'.crt';
+        $file = Utils\System::getTempDir().DIRECTORY_SEPARATOR.sha1($certData).'.crt';
         if (!file_exists($file)) {
-            System::writeFile($file, $certData);
+            Utils\System::writeFile($file, $certData);
         }
 
-        $spKeyCertFile = Config::getCertPath($spMetadata->getString('privatekey'));
+        $spKeyCertFile = Utils\Config::getCertPath($spMetadata->getString('privatekey'));
 
         $opts = [
             'ssl' => [
@@ -182,8 +178,8 @@ class Artifact
 
         // Fetch the artifact
         /** @var string $response */
-        $response = HTTP::fetch($url, $opts);
-        XML::debugSAMLMessage($response, 'in');
+        $response = Utils\HTTP::fetch($url, $opts);
+        Utils\XML::debugSAMLMessage($response, 'in');
 
         // Find the response in the SOAP message
         $response = self::extractResponse($response);
diff --git a/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php b/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php
index bc1a4b04f8580e135f6be3a4ccace51e2377c84c..89c3640df6370cec4a9376f1bbf929317fb135eb 100644
--- a/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php
+++ b/lib/SimpleSAML/Bindings/Shib13/HTTPPost.php
@@ -11,9 +11,9 @@
 namespace SimpleSAML\Bindings\Shib13;
 
 use SAML2\DOMDocumentFactory;
-use SimpleSAML\Utils\Crypto;
-use SimpleSAML\Utils\HTTP;
-use SimpleSAML\Utils\XML;
+use SimpleSAML\Configuration;
+use SimpleSAML\Metadata\MetaDataStorageHandler;
+use SimpleSAML\Utils;
 use SimpleSAML\XML\Shib13\AuthnResponse;
 use SimpleSAML\XML\Signer;
 
@@ -37,8 +37,8 @@ class HTTPPost
      * @param \SimpleSAML\Metadata\MetaDataStorageHandler $metadatastore A store where to find metadata.
      */
     public function __construct(
-        \SimpleSAML\Configuration $configuration,
-        \SimpleSAML\Metadata\MetaDataStorageHandler $metadatastore
+        Configuration $configuration,
+        MetaDataStorageHandler $metadatastore
     ) {
         $this->configuration = $configuration;
         $this->metadata = $metadatastore;
@@ -57,15 +57,15 @@ class HTTPPost
      */
     public function sendResponse(
         $response,
-        \SimpleSAML\Configuration $idpmd,
-        \SimpleSAML\Configuration $spmd,
+        Configuration $idpmd,
+        Configuration $spmd,
         $relayState,
         $shire
     ) {
-        XML::checkSAMLMessage($response, 'saml11');
+        Utils\XML::checkSAMLMessage($response, 'saml11');
 
-        $privatekey = Crypto::loadPrivateKey($idpmd, true);
-        $publickey = Crypto::loadPublicKey($idpmd, true);
+        $privatekey = Utils\Crypto::loadPrivateKey($idpmd, true);
+        $publickey = Utils\Crypto::loadPublicKey($idpmd, true);
 
         $responsedom = DOMDocumentFactory::fromString(str_replace("\r", "", $response));
 
@@ -102,7 +102,7 @@ class HTTPPost
         if ($signResponse) {
             // sign the response - this must be done after encrypting the assertion
             // we insert the signature before the saml2p:Status element
-            $statusElements = XML::getDOMChildren($responseroot, 'Status', '@saml1p');
+            $statusElements = Utils\XML::getDOMChildren($responseroot, 'Status', '@saml1p');
             assert(count($statusElements) === 1);
             $signer->sign($responseroot, $responseroot, $statusElements[0]);
         } else {
@@ -112,9 +112,9 @@ class HTTPPost
 
         $response = $responsedom->saveXML();
 
-        XML::debugSAMLMessage($response, 'out');
+        Utils\XML::debugSAMLMessage($response, 'out');
 
-        HTTP::submitPOSTData($shire, [
+        Utils\HTTP::submitPOSTData($shire, [
             'TARGET'       => $relayState,
             'SAMLResponse' => base64_encode($response),
         ]);
@@ -138,9 +138,9 @@ class HTTPPost
         $rawResponse = $post['SAMLResponse'];
         $samlResponseXML = base64_decode($rawResponse);
 
-        XML::debugSAMLMessage($samlResponseXML, 'in');
+        Utils\XML::debugSAMLMessage($samlResponseXML, 'in');
 
-        XML::checkSAMLMessage($samlResponseXML, 'saml11');
+        Utils\XML::checkSAMLMessage($samlResponseXML, 'saml11');
 
         $samlResponse = new AuthnResponse();
         $samlResponse->setXML($samlResponseXML);
diff --git a/lib/SimpleSAML/Configuration.php b/lib/SimpleSAML/Configuration.php
index b7150dd894c5c9fba5b7034e4f8560af97767241..95077aed9df248598b3128bf2d24d056a7152676 100644
--- a/lib/SimpleSAML/Configuration.php
+++ b/lib/SimpleSAML/Configuration.php
@@ -2,7 +2,9 @@
 
 namespace SimpleSAML;
 
-use SimpleSAML\Utils\System;
+use SAML2\Constants;
+use SimpleSAML\Error;
+use SimpleSAML\Utils;
 
 /**
  * Configuration of SimpleSAMLphp
@@ -579,7 +581,7 @@ class Configuration implements Utils\ClearableState
 
         assert(is_string($path));
 
-        return System::resolvePath($path, $this->getBaseDir());
+        return Utils\System::resolvePath($path, $this->getBaseDir());
     }
 
 
@@ -1105,11 +1107,11 @@ class Configuration implements Utils\ClearableState
             case 'saml20-idp-remote:SingleSignOnService':
             case 'saml20-idp-remote:SingleLogoutService':
             case 'saml20-sp-remote:SingleLogoutService':
-                return \SAML2\Constants::BINDING_HTTP_REDIRECT;
+                return Constants::BINDING_HTTP_REDIRECT;
             case 'saml20-sp-remote:AssertionConsumerService':
-                return \SAML2\Constants::BINDING_HTTP_POST;
+                return Constants::BINDING_HTTP_POST;
             case 'saml20-idp-remote:ArtifactResolutionService':
-                return \SAML2\Constants::BINDING_SOAP;
+                return Constants::BINDING_SOAP;
             case 'shib13-idp-remote:SingleSignOnService':
                 return 'urn:mace:shibboleth:1.0:profiles:AuthnRequest';
             case 'shib13-sp-remote:AssertionConsumerService':
diff --git a/lib/SimpleSAML/Database.php b/lib/SimpleSAML/Database.php
index 33c760098c81ce785a254e52c2f03569c854d128..685fe568f7472f898688aa67e3274e4b5635f818 100644
--- a/lib/SimpleSAML/Database.php
+++ b/lib/SimpleSAML/Database.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML;
 
+use PDO;
+use PDOException;
+
 /**
  * This file implements functions to read and write to a group of database servers.
  *
@@ -77,7 +80,7 @@ class Database
     {
         $driverOptions = $config->getArray('database.driver_options', []);
         if ($config->getBoolean('database.persistent', true)) {
-            $driverOptions = [\PDO::ATTR_PERSISTENT => true];
+            $driverOptions = [PDO::ATTR_PERSISTENT => true];
         }
 
         // connect to the master
@@ -144,11 +147,11 @@ class Database
     private function connect($dsn, $username, $password, $options)
     {
         try {
-            $db = new \PDO($dsn, $username, $password, $options);
-            $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
+            $db = new PDO($dsn, $username, $password, $options);
+            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
             return $db;
-        } catch (\PDOException $e) {
+        } catch (PDOException $e) {
             throw new \Exception("Database error: ".$e->getMessage());
         }
     }
@@ -205,16 +208,16 @@ class Database
 
             foreach ($params as $param => $value) {
                 if (is_array($value)) {
-                    $query->bindValue(":$param", $value[0], ($value[1]) ? $value[1] : \PDO::PARAM_STR);
+                    $query->bindValue(":$param", $value[0], ($value[1]) ? $value[1] : PDO::PARAM_STR);
                 } else {
-                    $query->bindValue(":$param", $value, \PDO::PARAM_STR);
+                    $query->bindValue(":$param", $value, PDO::PARAM_STR);
                 }
             }
 
             $query->execute();
 
             return $query;
-        } catch (\PDOException $e) {
+        } catch (PDOException $e) {
             $this->lastError = $db->errorInfo();
             throw new \Exception("Database error: ".$e->getMessage());
         }
@@ -237,7 +240,7 @@ class Database
 
         try {
             return $db->exec($stmt);
-        } catch (\PDOException $e) {
+        } catch (PDOException $e) {
             $this->lastError = $db->errorInfo();
             throw new \Exception("Database error: ".$e->getMessage());
         }
diff --git a/lib/SimpleSAML/Error/Assertion.php b/lib/SimpleSAML/Error/Assertion.php
index 691f2c90410b5fa38fd78f1513ca097f9b08d964..7e3581955d41a5bd2ee60ca017b642848f204579 100644
--- a/lib/SimpleSAML/Error/Assertion.php
+++ b/lib/SimpleSAML/Error/Assertion.php
@@ -60,7 +60,7 @@ class Assertion extends Exception
 
         assert_options(ASSERT_WARNING, 0);
         assert_options(ASSERT_QUIET_EVAL, 0);
-        assert_options(ASSERT_CALLBACK, ['\SimpleSAML\Error\Assertion', 'onAssertion']);
+        assert_options(ASSERT_CALLBACK, [Assertion::class, 'onAssertion']);
     }
 
 
diff --git a/lib/SimpleSAML/Error/CriticalConfigurationError.php b/lib/SimpleSAML/Error/CriticalConfigurationError.php
index 064a30fb3cf3c1cfaa3f193952af485bf963c07e..f078ee69579b3cf2108abc15025c72fcc28bc67b 100644
--- a/lib/SimpleSAML/Error/CriticalConfigurationError.php
+++ b/lib/SimpleSAML/Error/CriticalConfigurationError.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Error;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Utils;
+
 /**
  * This exception represents a configuration error that we cannot recover from.
  *
@@ -30,7 +34,7 @@ class CriticalConfigurationError extends ConfigurationError
      */
     private static $minimum_config = [
         'logging.handler' => 'errorlog',
-        'logging.level'  => \SimpleSAML\Logger::DEBUG,
+        'logging.level'  => Logger::DEBUG,
         'errorreporting' => false,
         'debug'          => true,
     ];
@@ -47,10 +51,10 @@ class CriticalConfigurationError extends ConfigurationError
     {
         if ($config === null) {
             $config = self::$minimum_config;
-            $config['baseurlpath'] = \SimpleSAML\Utils\HTTP::guessBasePath();
+            $config['baseurlpath'] = Utils\HTTP::guessBasePath();
         }
 
-        \SimpleSAML\Configuration::loadFromArray(
+        Configuration::loadFromArray(
             $config,
             '',
             'simplesaml'
diff --git a/lib/SimpleSAML/Error/Error.php b/lib/SimpleSAML/Error/Error.php
index 7d56196be750004d891a227e351eea3ba6bd5108..8fa391cd7182b8329e92069565bf6a3218c880e4 100644
--- a/lib/SimpleSAML/Error/Error.php
+++ b/lib/SimpleSAML/Error/Error.php
@@ -2,6 +2,12 @@
 
 namespace SimpleSAML\Error;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+use SimpleSAML\XHTML\Template;
+
 /**
  * Class that wraps SimpleSAMLphp errors in exceptions.
  *
@@ -175,10 +181,10 @@ class Error extends Exception
         $etrace = implode("\n", $data);
 
         $reportId = bin2hex(openssl_random_pseudo_bytes(4));
-        \SimpleSAML\Logger::error('Error report with id '.$reportId.' generated.');
+        Logger::error('Error report with id '.$reportId.' generated.');
 
-        $config = \SimpleSAML\Configuration::getInstance();
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $config = Configuration::getInstance();
+        $session = Session::getSessionFromRequest();
 
         if (isset($_SERVER['HTTP_REFERER'])) {
             $referer = $_SERVER['HTTP_REFERER'];
@@ -195,7 +201,7 @@ class Error extends Exception
             'exceptionTrace' => $etrace,
             'reportId'       => $reportId,
             'trackId'        => $session->getTrackID(),
-            'url'            => \SimpleSAML\Utils\HTTP::getSelfURLNoQuery(),
+            'url'            => Utils\HTTP::getSelfURLNoQuery(),
             'version'        => $config->getVersion(),
             'referer'        => $referer,
         ];
@@ -219,7 +225,7 @@ class Error extends Exception
         $this->logError();
 
         $errorData = $this->saveError();
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
 
         $data = [];
         $data['showerrors'] = $config->getBoolean('showerrors', true);
@@ -237,12 +243,12 @@ class Error extends Exception
             $config->getString('technicalcontact_email', 'na@example.org') !== 'na@example.org'
         ) {
             // enable error reporting
-            $baseurl = \SimpleSAML\Utils\HTTP::getBaseURL();
+            $baseurl = Utils\HTTP::getBaseURL();
             $data['errorReportAddress'] = $baseurl.'errorreport.php';
         }
 
         $data['email'] = '';
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $authorities = $session->getAuthorities();
         foreach ($authorities as $authority) {
             $attributes = $session->getAuthData($authority, 'Attributes');
@@ -258,10 +264,11 @@ class Error extends Exception
             call_user_func($show_function, $config, $data);
             assert(false);
         } else {
-            $t = new \SimpleSAML\XHTML\Template($config, 'error.php', 'errors');
+            $t = new Template($config, 'error.php', 'errors');
+            $translator = $t->getTranslator();
             $t->data = array_merge($t->data, $data);
-            $t->data['dictTitleTranslated'] = $t->getTranslator()->t($t->data['dictTitle']);
-            $t->data['dictDescrTranslated'] = $t->getTranslator()->t($t->data['dictDescr'], $t->data['parameters']);
+            $t->data['dictTitleTranslated'] = $translator->t($t->data['dictTitle']);
+            $t->data['dictDescrTranslated'] = $translator->t($t->data['dictDescr'], $t->data['parameters']);
             $t->show();
         }
 
diff --git a/lib/SimpleSAML/Error/ErrorCodes.php b/lib/SimpleSAML/Error/ErrorCodes.php
index d15f8c46ff268d03933ec39b011f03f3547fac90..75e7f1b8567e211d91fd000d297de7ed50a96b04 100644
--- a/lib/SimpleSAML/Error/ErrorCodes.php
+++ b/lib/SimpleSAML/Error/ErrorCodes.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Error;
 
+use SimpleSAML\Locale\Translate;
+
 /**
  * Class that maps SimpleSAMLphp error codes to translateable strings.
  *
@@ -19,39 +21,39 @@ class ErrorCodes
     final public static function defaultGetAllErrorCodeTitles()
     {
         return [
-            'ACSPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:title_ACSPARAMS}'),
-            'ARSPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:title_ARSPARAMS}'),
-            'AUTHSOURCEERROR' => \SimpleSAML\Locale\Translate::noop('{errors:title_AUTHSOURCEERROR}'),
-            'BADREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:title_BADREQUEST}'),
-            'CASERROR' => \SimpleSAML\Locale\Translate::noop('{errors:title_CASERROR}'),
-            'CONFIG' => \SimpleSAML\Locale\Translate::noop('{errors:title_CONFIG}'),
-            'CREATEREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:title_CREATEREQUEST}'),
-            'DISCOPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:title_DISCOPARAMS}'),
-            'GENERATEAUTHNRESPONSE' => \SimpleSAML\Locale\Translate::noop('{errors:title_GENERATEAUTHNRESPONSE}'),
-            'INVALIDCERT' => \SimpleSAML\Locale\Translate::noop('{errors:title_INVALIDCERT}'),
-            'LDAPERROR' => \SimpleSAML\Locale\Translate::noop('{errors:title_LDAPERROR}'),
-            'LOGOUTINFOLOST' => \SimpleSAML\Locale\Translate::noop('{errors:title_LOGOUTINFOLOST}'),
-            'LOGOUTREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:title_LOGOUTREQUEST}'),
-            'MEMCACHEDOWN' => \SimpleSAML\Locale\Translate::noop('{errors:title_MEMCACHEDOWN}'),
-            'METADATA' => \SimpleSAML\Locale\Translate::noop('{errors:title_METADATA}'),
-            'METADATANOTFOUND' => \SimpleSAML\Locale\Translate::noop('{errors:title_METADATANOTFOUND}'),
-            'NOACCESS' => \SimpleSAML\Locale\Translate::noop('{errors:title_NOACCESS}'),
-            'NOCERT' => \SimpleSAML\Locale\Translate::noop('{errors:title_NOCERT}'),
-            'NORELAYSTATE' => \SimpleSAML\Locale\Translate::noop('{errors:title_NORELAYSTATE}'),
-            'NOSTATE' => \SimpleSAML\Locale\Translate::noop('{errors:title_NOSTATE}'),
-            'NOTFOUND' => \SimpleSAML\Locale\Translate::noop('{errors:title_NOTFOUND}'),
-            'NOTFOUNDREASON' => \SimpleSAML\Locale\Translate::noop('{errors:title_NOTFOUNDREASON}'),
-            'NOTSET' => \SimpleSAML\Locale\Translate::noop('{errors:title_NOTSET}'),
-            'NOTVALIDCERT' => \SimpleSAML\Locale\Translate::noop('{errors:title_NOTVALIDCERT}'),
-            'PROCESSASSERTION' => \SimpleSAML\Locale\Translate::noop('{errors:title_PROCESSASSERTION}'),
-            'PROCESSAUTHNREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:title_PROCESSAUTHNREQUEST}'),
-            'RESPONSESTATUSNOSUCCESS' => \SimpleSAML\Locale\Translate::noop('{errors:title_RESPONSESTATUSNOSUCCESS}'),
-            'SLOSERVICEPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:title_SLOSERVICEPARAMS}'),
-            'SSOPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:title_SSOPARAMS}'),
-            'UNHANDLEDEXCEPTION' => \SimpleSAML\Locale\Translate::noop('{errors:title_UNHANDLEDEXCEPTION}'),
-            'UNKNOWNCERT' => \SimpleSAML\Locale\Translate::noop('{errors:title_UNKNOWNCERT}'),
-            'USERABORTED' => \SimpleSAML\Locale\Translate::noop('{errors:title_USERABORTED}'),
-            'WRONGUSERPASS' => \SimpleSAML\Locale\Translate::noop('{errors:title_WRONGUSERPASS}'),
+            'ACSPARAMS' => Translate::noop('{errors:title_ACSPARAMS}'),
+            'ARSPARAMS' => Translate::noop('{errors:title_ARSPARAMS}'),
+            'AUTHSOURCEERROR' => Translate::noop('{errors:title_AUTHSOURCEERROR}'),
+            'BADREQUEST' => Translate::noop('{errors:title_BADREQUEST}'),
+            'CASERROR' => Translate::noop('{errors:title_CASERROR}'),
+            'CONFIG' => Translate::noop('{errors:title_CONFIG}'),
+            'CREATEREQUEST' => Translate::noop('{errors:title_CREATEREQUEST}'),
+            'DISCOPARAMS' => Translate::noop('{errors:title_DISCOPARAMS}'),
+            'GENERATEAUTHNRESPONSE' => Translate::noop('{errors:title_GENERATEAUTHNRESPONSE}'),
+            'INVALIDCERT' => Translate::noop('{errors:title_INVALIDCERT}'),
+            'LDAPERROR' => Translate::noop('{errors:title_LDAPERROR}'),
+            'LOGOUTINFOLOST' => Translate::noop('{errors:title_LOGOUTINFOLOST}'),
+            'LOGOUTREQUEST' => Translate::noop('{errors:title_LOGOUTREQUEST}'),
+            'MEMCACHEDOWN' => Translate::noop('{errors:title_MEMCACHEDOWN}'),
+            'METADATA' => Translate::noop('{errors:title_METADATA}'),
+            'METADATANOTFOUND' => Translate::noop('{errors:title_METADATANOTFOUND}'),
+            'NOACCESS' => Translate::noop('{errors:title_NOACCESS}'),
+            'NOCERT' => Translate::noop('{errors:title_NOCERT}'),
+            'NORELAYSTATE' => Translate::noop('{errors:title_NORELAYSTATE}'),
+            'NOSTATE' => Translate::noop('{errors:title_NOSTATE}'),
+            'NOTFOUND' => Translate::noop('{errors:title_NOTFOUND}'),
+            'NOTFOUNDREASON' => Translate::noop('{errors:title_NOTFOUNDREASON}'),
+            'NOTSET' => Translate::noop('{errors:title_NOTSET}'),
+            'NOTVALIDCERT' => Translate::noop('{errors:title_NOTVALIDCERT}'),
+            'PROCESSASSERTION' => Translate::noop('{errors:title_PROCESSASSERTION}'),
+            'PROCESSAUTHNREQUEST' => Translate::noop('{errors:title_PROCESSAUTHNREQUEST}'),
+            'RESPONSESTATUSNOSUCCESS' => Translate::noop('{errors:title_RESPONSESTATUSNOSUCCESS}'),
+            'SLOSERVICEPARAMS' => Translate::noop('{errors:title_SLOSERVICEPARAMS}'),
+            'SSOPARAMS' => Translate::noop('{errors:title_SSOPARAMS}'),
+            'UNHANDLEDEXCEPTION' => Translate::noop('{errors:title_UNHANDLEDEXCEPTION}'),
+            'UNKNOWNCERT' => Translate::noop('{errors:title_UNKNOWNCERT}'),
+            'USERABORTED' => Translate::noop('{errors:title_USERABORTED}'),
+            'WRONGUSERPASS' => Translate::noop('{errors:title_WRONGUSERPASS}'),
         ];
     }
 
@@ -77,39 +79,39 @@ class ErrorCodes
     final public static function defaultGetAllErrorCodeDescriptions()
     {
         return [
-            'ACSPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_ACSPARAMS}'),
-            'ARSPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_ARSPARAMS}'),
-            'AUTHSOURCEERROR' => \SimpleSAML\Locale\Translate::noop('{errors:descr_AUTHSOURCEERROR}'),
-            'BADREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:descr_BADREQUEST}'),
-            'CASERROR' => \SimpleSAML\Locale\Translate::noop('{errors:descr_CASERROR}'),
-            'CONFIG' => \SimpleSAML\Locale\Translate::noop('{errors:descr_CONFIG}'),
-            'CREATEREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:descr_CREATEREQUEST}'),
-            'DISCOPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_DISCOPARAMS}'),
-            'GENERATEAUTHNRESPONSE' => \SimpleSAML\Locale\Translate::noop('{errors:descr_GENERATEAUTHNRESPONSE}'),
-            'INVALIDCERT' => \SimpleSAML\Locale\Translate::noop('{errors:descr_INVALIDCERT}'),
-            'LDAPERROR' => \SimpleSAML\Locale\Translate::noop('{errors:descr_LDAPERROR}'),
-            'LOGOUTINFOLOST' => \SimpleSAML\Locale\Translate::noop('{errors:descr_LOGOUTINFOLOST}'),
-            'LOGOUTREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:descr_LOGOUTREQUEST}'),
-            'MEMCACHEDOWN' => \SimpleSAML\Locale\Translate::noop('{errors:descr_MEMCACHEDOWN}'),
-            'METADATA' => \SimpleSAML\Locale\Translate::noop('{errors:descr_METADATA}'),
-            'METADATANOTFOUND' => \SimpleSAML\Locale\Translate::noop('{errors:descr_METADATANOTFOUND}'),
-            'NOACCESS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NOACCESS}'),
-            'NOCERT' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NOCERT}'),
-            'NORELAYSTATE' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NORELAYSTATE}'),
-            'NOSTATE' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NOSTATE}'),
-            'NOTFOUND' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NOTFOUND}'),
-            'NOTFOUNDREASON' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NOTFOUNDREASON}'),
-            'NOTSET' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NOTSET}'),
-            'NOTVALIDCERT' => \SimpleSAML\Locale\Translate::noop('{errors:descr_NOTVALIDCERT}'),
-            'PROCESSASSERTION' => \SimpleSAML\Locale\Translate::noop('{errors:descr_PROCESSASSERTION}'),
-            'PROCESSAUTHNREQUEST' => \SimpleSAML\Locale\Translate::noop('{errors:descr_PROCESSAUTHNREQUEST}'),
-            'RESPONSESTATUSNOSUCCESS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_RESPONSESTATUSNOSUCCESS}'),
-            'SLOSERVICEPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_SLOSERVICEPARAMS}'),
-            'SSOPARAMS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_SSOPARAMS}'),
-            'UNHANDLEDEXCEPTION' => \SimpleSAML\Locale\Translate::noop('{errors:descr_UNHANDLEDEXCEPTION}'),
-            'UNKNOWNCERT' => \SimpleSAML\Locale\Translate::noop('{errors:descr_UNKNOWNCERT}'),
-            'USERABORTED' => \SimpleSAML\Locale\Translate::noop('{errors:descr_USERABORTED}'),
-            'WRONGUSERPASS' => \SimpleSAML\Locale\Translate::noop('{errors:descr_WRONGUSERPASS}'),
+            'ACSPARAMS' => Translate::noop('{errors:descr_ACSPARAMS}'),
+            'ARSPARAMS' => Translate::noop('{errors:descr_ARSPARAMS}'),
+            'AUTHSOURCEERROR' => Translate::noop('{errors:descr_AUTHSOURCEERROR}'),
+            'BADREQUEST' => Translate::noop('{errors:descr_BADREQUEST}'),
+            'CASERROR' => Translate::noop('{errors:descr_CASERROR}'),
+            'CONFIG' => Translate::noop('{errors:descr_CONFIG}'),
+            'CREATEREQUEST' => Translate::noop('{errors:descr_CREATEREQUEST}'),
+            'DISCOPARAMS' => Translate::noop('{errors:descr_DISCOPARAMS}'),
+            'GENERATEAUTHNRESPONSE' => Translate::noop('{errors:descr_GENERATEAUTHNRESPONSE}'),
+            'INVALIDCERT' => Translate::noop('{errors:descr_INVALIDCERT}'),
+            'LDAPERROR' => Translate::noop('{errors:descr_LDAPERROR}'),
+            'LOGOUTINFOLOST' => Translate::noop('{errors:descr_LOGOUTINFOLOST}'),
+            'LOGOUTREQUEST' => Translate::noop('{errors:descr_LOGOUTREQUEST}'),
+            'MEMCACHEDOWN' => Translate::noop('{errors:descr_MEMCACHEDOWN}'),
+            'METADATA' => Translate::noop('{errors:descr_METADATA}'),
+            'METADATANOTFOUND' => Translate::noop('{errors:descr_METADATANOTFOUND}'),
+            'NOACCESS' => Translate::noop('{errors:descr_NOACCESS}'),
+            'NOCERT' => Translate::noop('{errors:descr_NOCERT}'),
+            'NORELAYSTATE' => Translate::noop('{errors:descr_NORELAYSTATE}'),
+            'NOSTATE' => Translate::noop('{errors:descr_NOSTATE}'),
+            'NOTFOUND' => Translate::noop('{errors:descr_NOTFOUND}'),
+            'NOTFOUNDREASON' => Translate::noop('{errors:descr_NOTFOUNDREASON}'),
+            'NOTSET' => Translate::noop('{errors:descr_NOTSET}'),
+            'NOTVALIDCERT' => Translate::noop('{errors:descr_NOTVALIDCERT}'),
+            'PROCESSASSERTION' => Translate::noop('{errors:descr_PROCESSASSERTION}'),
+            'PROCESSAUTHNREQUEST' => Translate::noop('{errors:descr_PROCESSAUTHNREQUEST}'),
+            'RESPONSESTATUSNOSUCCESS' => Translate::noop('{errors:descr_RESPONSESTATUSNOSUCCESS}'),
+            'SLOSERVICEPARAMS' => Translate::noop('{errors:descr_SLOSERVICEPARAMS}'),
+            'SSOPARAMS' => Translate::noop('{errors:descr_SSOPARAMS}'),
+            'UNHANDLEDEXCEPTION' => Translate::noop('{errors:descr_UNHANDLEDEXCEPTION}'),
+            'UNKNOWNCERT' => Translate::noop('{errors:descr_UNKNOWNCERT}'),
+            'USERABORTED' => Translate::noop('{errors:descr_USERABORTED}'),
+            'WRONGUSERPASS' => Translate::noop('{errors:descr_WRONGUSERPASS}'),
         ];
     }
 
diff --git a/lib/SimpleSAML/Error/Exception.php b/lib/SimpleSAML/Error/Exception.php
index 78267a17c7fef8c3d963f01047cb7a3793bb299c..18aabf398edfd659297df534aac8f1f8e0799d90 100644
--- a/lib/SimpleSAML/Error/Exception.php
+++ b/lib/SimpleSAML/Error/Exception.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Error;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+
 /**
  * Base class for SimpleSAMLphp Exceptions
  *
@@ -168,7 +171,7 @@ class Exception extends \Exception
     public function formatBacktrace($anonymize = false)
     {
         $ret = [];
-        $basedir = \SimpleSAML\Configuration::getInstance()->getBaseDir();
+        $basedir = Configuration::getInstance()->getBaseDir();
 
         $e = $this;
         do {
@@ -197,10 +200,10 @@ class Exception extends \Exception
      * @param int $level
      * @return void
      */
-    protected function logBacktrace($level = \SimpleSAML\Logger::DEBUG)
+    protected function logBacktrace($level = Logger::DEBUG)
     {
         // see if debugging is enabled for backtraces
-        $debug = \SimpleSAML\Configuration::getInstance()->getArrayize('debug', ['backtraces' => false]);
+        $debug = Configuration::getInstance()->getArrayize('debug', ['backtraces' => false]);
 
         if (!(in_array('backtraces', $debug, true) // implicitly enabled
             || (array_key_exists('backtraces', $debug) && $debug['backtraces'] === true)
@@ -213,12 +216,12 @@ class Exception extends \Exception
 
         $backtrace = $this->formatBacktrace();
 
-        $callback = ['\SimpleSAML\Logger'];
+        $callback = [Logger::class];
         $functions = [
-            \SimpleSAML\Logger::ERR     => 'error',
-            \SimpleSAML\Logger::WARNING => 'warning',
-            \SimpleSAML\Logger::INFO    => 'info',
-            \SimpleSAML\Logger::DEBUG   => 'debug',
+            Logger::ERR     => 'error',
+            Logger::WARNING => 'warning',
+            Logger::INFO    => 'info',
+            Logger::DEBUG   => 'debug',
         ];
         $callback[] = $functions[$level];
 
@@ -239,10 +242,10 @@ class Exception extends \Exception
     public function log($default_level)
     {
         $fn = [
-            \SimpleSAML\Logger::ERR     => 'logError',
-            \SimpleSAML\Logger::WARNING => 'logWarning',
-            \SimpleSAML\Logger::INFO    => 'logInfo',
-            \SimpleSAML\Logger::DEBUG   => 'logDebug',
+            Logger::ERR     => 'logError',
+            Logger::WARNING => 'logWarning',
+            Logger::INFO    => 'logInfo',
+            Logger::DEBUG   => 'logDebug',
         ];
         call_user_func([$this, $fn[$default_level]], $default_level);
     }
@@ -256,8 +259,8 @@ class Exception extends \Exception
      */
     public function logError()
     {
-        \SimpleSAML\Logger::error($this->getClass().': '.$this->getMessage());
-        $this->logBacktrace(\SimpleSAML\Logger::ERR);
+        Logger::error($this->getClass().': '.$this->getMessage());
+        $this->logBacktrace(Logger::ERR);
     }
 
 
@@ -269,8 +272,8 @@ class Exception extends \Exception
      */
     public function logWarning()
     {
-        \SimpleSAML\Logger::warning($this->getClass().': '.$this->getMessage());
-        $this->logBacktrace(\SimpleSAML\Logger::WARNING);
+        Logger::warning($this->getClass().': '.$this->getMessage());
+        $this->logBacktrace(Logger::WARNING);
     }
 
 
@@ -282,8 +285,8 @@ class Exception extends \Exception
      */
     public function logInfo()
     {
-        \SimpleSAML\Logger::info($this->getClass().': '.$this->getMessage());
-        $this->logBacktrace(\SimpleSAML\Logger::INFO);
+        Logger::info($this->getClass().': '.$this->getMessage());
+        $this->logBacktrace(Logger::INFO);
     }
 
 
@@ -295,8 +298,8 @@ class Exception extends \Exception
      */
     public function logDebug()
     {
-        \SimpleSAML\Logger::debug($this->getClass().': '.$this->getMessage());
-        $this->logBacktrace(\SimpleSAML\Logger::DEBUG);
+        Logger::debug($this->getClass().': '.$this->getMessage());
+        $this->logBacktrace(Logger::DEBUG);
     }
 
 
diff --git a/lib/SimpleSAML/Error/NotFound.php b/lib/SimpleSAML/Error/NotFound.php
index 0e618526962b0a596948e394b1f04abf046c1298..187b658d09ab559869556e4f4ba59536f27c4a99 100644
--- a/lib/SimpleSAML/Error/NotFound.php
+++ b/lib/SimpleSAML/Error/NotFound.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Error;
 
+use SimpleSAML\Utils;
+
 /**
  * Exception which will show a 404 Not Found error page.
  *
@@ -29,7 +31,7 @@ class NotFound extends Error
     {
         assert($reason === null || is_string($reason));
 
-        $url = \SimpleSAML\Utils\HTTP::getSelfURL();
+        $url = Utils\HTTP::getSelfURL();
 
         if ($reason === null) {
             parent::__construct(['NOTFOUND', '%URL%' => $url]);
diff --git a/lib/SimpleSAML/HTTP/Router.php b/lib/SimpleSAML/HTTP/Router.php
index 699d3a752bbcfc93c30b655ea11f7665a2f3ea71..cb49e805793ca35bb685f011c39cdba24c06c3ce 100644
--- a/lib/SimpleSAML/HTTP/Router.php
+++ b/lib/SimpleSAML/HTTP/Router.php
@@ -3,6 +3,7 @@
 namespace SimpleSAML\HTTP;
 
 use SimpleSAML\Configuration;
+use SimpleSAML\Module\ControllerResolver;
 use SimpleSAML\Session;
 
 use Symfony\Component\EventDispatcher\EventDispatcher;
@@ -54,7 +55,7 @@ class Router
     {
         $this->arguments = new ArgumentResolver();
         $this->context = new RequestContext();
-        $this->resolver = new \SimpleSAML\Module\ControllerResolver($module);
+        $this->resolver = new ControllerResolver($module);
         $this->dispatcher = new EventDispatcher();
     }
 
diff --git a/lib/SimpleSAML/IdP.php b/lib/SimpleSAML/IdP.php
index 6a963c30e048101030c366ce54f364a1b6744191..a68d95b859305a634f2344a238d3361a81839337 100644
--- a/lib/SimpleSAML/IdP.php
+++ b/lib/SimpleSAML/IdP.php
@@ -2,7 +2,11 @@
 
 namespace SimpleSAML;
 
-use SimpleSAML\Error\Exception;
+use SimpleSAML\Auth;
+use SimpleSAML\Error;
+use SimpleSAML\Metadata\MetaDataStorageHandler;
+use SimpleSAML\Module\saml\Error\NoPassive;
+use SimpleSAML\Utils;
 
 /**
  * IdP class.
@@ -57,7 +61,7 @@ class IdP
      *
      * @param string $id The identifier of this IdP.
      *
-     * @throws Exception If the IdP is disabled or no such auth source was found.
+     * @throws \SimpleSAML\Error\Exception If the IdP is disabled or no such auth source was found.
      */
     private function __construct($id)
     {
@@ -65,22 +69,22 @@ class IdP
 
         $this->id = $id;
 
-        $metadata = Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $globalConfig = Configuration::getInstance();
 
         if (substr($id, 0, 6) === 'saml2:') {
             if (!$globalConfig->getBoolean('enable.saml20-idp', false)) {
-                throw new Exception('enable.saml20-idp disabled in config.php.');
+                throw new Error\Exception('enable.saml20-idp disabled in config.php.');
             }
             $this->config = $metadata->getMetaDataConfig(substr($id, 6), 'saml20-idp-hosted');
         } elseif (substr($id, 0, 6) === 'saml1:') {
             if (!$globalConfig->getBoolean('enable.shib13-idp', false)) {
-                throw new Exception('enable.shib13-idp disabled in config.php.');
+                throw new Error\Exception('enable.shib13-idp disabled in config.php.');
             }
             $this->config = $metadata->getMetaDataConfig(substr($id, 6), 'shib13-idp-hosted');
         } elseif (substr($id, 0, 5) === 'adfs:') {
             if (!$globalConfig->getBoolean('enable.adfs-idp', false)) {
-                throw new Exception('enable.adfs-idp disabled in config.php.');
+                throw new Error\Exception('enable.adfs-idp disabled in config.php.');
             }
             $this->config = $metadata->getMetaDataConfig(substr($id, 5), 'adfs-idp-hosted');
 
@@ -103,7 +107,7 @@ class IdP
         if (Auth\Source::getById($auth) !== null) {
             $this->authSource = new Auth\Simple($auth);
         } else {
-            throw new Exception('No such "'.$auth.'" auth source found.');
+            throw new Error\Exception('No such "'.$auth.'" auth source found.');
         }
     }
 
@@ -179,7 +183,7 @@ class IdP
 
         $prefix = substr($assocId, 0, 4);
         $spEntityId = substr($assocId, strlen($prefix) + 1);
-        $metadata = Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
 
         if ($prefix === 'saml') {
             try {
@@ -276,7 +280,7 @@ class IdP
         assert(is_callable($state['Responder']));
 
         if (isset($state['core:SP'])) {
-            $session = \SimpleSAML\Session::getSessionFromRequest();
+            $session = Session::getSessionFromRequest();
             $session->setData(
                 'core:idp-ssotime',
                 $state['core:IdP'].';'.$state['core:SP'],
@@ -295,7 +299,7 @@ class IdP
      *
      * @param array $state The authentication request state array.
      *
-     * @throws Exception If we are not authenticated.
+     * @throws \SimpleSAML\Error\Exception If we are not authenticated.
      * @return void
      */
     public static function postAuth(array $state)
@@ -303,7 +307,7 @@ class IdP
         $idp = IdP::getByState($state);
 
         if (!$idp->isAuthenticated()) {
-            throw new Exception('Not authenticated.');
+            throw new Error\Exception('Not authenticated.');
         }
 
         $state['Attributes'] = $idp->authSource->getAttributes();
@@ -343,13 +347,13 @@ class IdP
      *
      * @param array &$state The authentication request state.
      *
-     * @throws Module\saml\Error\NoPassive If we were asked to do passive authentication.
+     * @throws \SimpleSAML\Module\saml\Error\NoPassive If we were asked to do passive authentication.
      * @return void
      */
     private function authenticate(array &$state)
     {
         if (isset($state['isPassive']) && (bool) $state['isPassive']) {
-            throw new Module\saml\Error\NoPassive('Passive authentication not supported.');
+            throw new NoPassive('Passive authentication not supported.');
         }
 
         $this->authSource->login($state);
@@ -416,8 +420,8 @@ class IdP
                 $this->reauthenticate($state);
             }
             $this->postAuth($state);
-        } catch (Exception $e) {
-            \SimpleSAML\Auth\State::throwException($state, $e);
+        } catch (Error\Exception $e) {
+            Auth\State::throwException($state, $e);
         } catch (\Exception $e) {
             $e = new Error\UnserializableException($e);
             Auth\State::throwException($state, $e);
@@ -444,7 +448,7 @@ class IdP
                 $handler = '\SimpleSAML\IdP\IFrameLogoutHandler';
                 break;
             default:
-                throw new Exception('Unknown logout handler: '.var_export($logouttype, true));
+                throw new Error\Exception('Unknown logout handler: '.var_export($logouttype, true));
         }
 
         return new $handler($this);
@@ -512,10 +516,10 @@ class IdP
      *
      * @param string                 $assocId The association that is terminated.
      * @param string|null            $relayState The RelayState from the start of the logout.
-     * @param Exception|null $error  The error that occurred during session termination (if any).
+     * @param \SimpleSAML\Error\Exception|null $error  The error that occurred during session termination (if any).
      * @return void
      */
-    public function handleLogoutResponse($assocId, $relayState, Exception $error = null)
+    public function handleLogoutResponse($assocId, $relayState, Error\Exception $error = null)
     {
         assert(is_string($assocId));
         assert(is_string($relayState) || $relayState === null);
diff --git a/lib/SimpleSAML/IdP/IFrameLogoutHandler.php b/lib/SimpleSAML/IdP/IFrameLogoutHandler.php
index 363fae8d35838c86f849b6848adec6505cba33ca..6a6aa90d52878743944ca93379fb6974346e71c2 100644
--- a/lib/SimpleSAML/IdP/IFrameLogoutHandler.php
+++ b/lib/SimpleSAML/IdP/IFrameLogoutHandler.php
@@ -2,8 +2,13 @@
 
 namespace SimpleSAML\IdP;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\IdP;
 use SimpleSAML\Module;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Utils;
+use SimpleSAML\XHTML\Template;
 
 /**
  * Class that handles iframe logout.
@@ -25,7 +30,7 @@ class IFrameLogoutHandler implements LogoutHandlerInterface
      *
      * @param \SimpleSAML\IdP $idp The IdP to log out from.
      */
-    public function __construct(\SimpleSAML\IdP $idp)
+    public function __construct(IdP $idp)
     {
         $this->idp = $idp;
     }
@@ -48,7 +53,7 @@ class IFrameLogoutHandler implements LogoutHandlerInterface
         }
 
         foreach ($associations as $id => &$association) {
-            $idp = \SimpleSAML\IdP::getByState($association);
+            $idp = IdP::getByState($association);
             $association['core:Logout-IFrame:Name'] = $idp->getSPName($id);
             $association['core:Logout-IFrame:State'] = 'onhold';
         }
@@ -66,14 +71,14 @@ class IFrameLogoutHandler implements LogoutHandlerInterface
         }
 
         $params = [
-            'id' => \SimpleSAML\Auth\State::saveState($state, 'core:Logout-IFrame'),
+            'id' => Auth\State::saveState($state, 'core:Logout-IFrame'),
         ];
         if (isset($state['core:Logout-IFrame:InitType'])) {
             $params['type'] = $state['core:Logout-IFrame:InitType'];
         }
 
         $url = Module::getModuleURL('core/idp/logout-iframe.php', $params);
-        HTTP::redirectTrustedURL($url);
+        Utils\HTTP::redirectTrustedURL($url);
     }
 
 
@@ -87,14 +92,14 @@ class IFrameLogoutHandler implements LogoutHandlerInterface
      * @param \SimpleSAML\Error\Exception|null $error The error that occurred during session termination (if any).
      * @return void
      */
-    public function onResponse($assocId, $relayState, \SimpleSAML\Error\Exception $error = null)
+    public function onResponse($assocId, $relayState, Error\Exception $error = null)
     {
         assert(is_string($assocId));
 
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $this->idp->terminateAssociation($assocId);
 
-        $t = new \SimpleSAML\XHTML\Template($config, 'IFrameLogoutHandler.twig');
+        $t = new Template($config, 'IFrameLogoutHandler.twig');
         $t->data['assocId'] = var_export($assocId, true);
         $t->data['spId'] = sha1($assocId);
         if (!is_null($error)) {
diff --git a/lib/SimpleSAML/IdP/LogoutHandlerInterface.php b/lib/SimpleSAML/IdP/LogoutHandlerInterface.php
index 3ac7a3d118c2b2b36acf2327172b8bacec51ea3a..fe52c00415a614b63e8d90ed32f526ebf2bffee2 100644
--- a/lib/SimpleSAML/IdP/LogoutHandlerInterface.php
+++ b/lib/SimpleSAML/IdP/LogoutHandlerInterface.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\IdP;
 
+use SimpleSAML\Error;
+use SimpleSAML\IdP;
+
 /**
  * Interface that all logout handlers must implement.
  *
@@ -15,7 +18,7 @@ interface LogoutHandlerInterface
      *
      * @param \SimpleSAML\IdP $idp The IdP we are logging out from.
      */
-    public function __construct(\SimpleSAML\IdP $idp);
+    public function __construct(IdP $idp);
 
 
     /**
@@ -40,5 +43,5 @@ interface LogoutHandlerInterface
      * @param \SimpleSAML\Error\Exception|null $error The error that occurred during session termination (if any).
      * @return void
      */
-    public function onResponse($assocId, $relayState, \SimpleSAML\Error\Exception $error = null);
+    public function onResponse($assocId, $relayState, Error\Exception $error = null);
 }
diff --git a/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php b/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php
index e6b1717e9058009c47cbf8e78df6068be4fe5fcd..7649ef75309f2f80d73d356bd6338d5080445627 100644
--- a/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php
+++ b/lib/SimpleSAML/IdP/TraditionalLogoutHandler.php
@@ -2,8 +2,11 @@
 
 namespace SimpleSAML\IdP;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Error;
+use SimpleSAML\IdP;
 use SimpleSAML\Logger;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Utils;
 
 /**
  * Class that handles traditional logout.
@@ -26,7 +29,7 @@ class TraditionalLogoutHandler implements LogoutHandlerInterface
      *
      * @param \SimpleSAML\IdP $idp The IdP to log out from.
      */
-    public function __construct(\SimpleSAML\IdP $idp)
+    public function __construct(IdP $idp)
     {
         $this->idp = $idp;
     }
@@ -47,15 +50,15 @@ class TraditionalLogoutHandler implements LogoutHandlerInterface
             $this->idp->finishLogout($state);
         }
 
-        $relayState = \SimpleSAML\Auth\State::saveState($state, 'core:LogoutTraditional', true);
+        $relayState = Auth\State::saveState($state, 'core:LogoutTraditional', true);
 
         $id = $association['id'];
         Logger::info('Logging out of '.var_export($id, true).'.');
 
         try {
-            $idp = \SimpleSAML\IdP::getByState($association);
+            $idp = IdP::getByState($association);
             $url = call_user_func([$association['Handler'], 'getLogoutURL'], $idp, $association, $relayState);
-            HTTP::redirectTrustedURL($url);
+            Utils\HTTP::redirectTrustedURL($url);
         } catch (\Exception $e) {
             Logger::warning('Unable to initialize logout to '.var_export($id, true).'.');
             $this->idp->terminateAssociation($id);
@@ -97,16 +100,16 @@ class TraditionalLogoutHandler implements LogoutHandlerInterface
      *
      * @throws \SimpleSAML\Error\Exception If the RelayState was lost during logout.
      */
-    public function onResponse($assocId, $relayState, \SimpleSAML\Error\Exception $error = null)
+    public function onResponse($assocId, $relayState, Error\Exception $error = null)
     {
         assert(is_string($assocId));
         assert(is_string($relayState) || $relayState === null);
 
         if ($relayState === null) {
-            throw new \SimpleSAML\Error\Exception('RelayState lost during logout.');
+            throw new Error\Exception('RelayState lost during logout.');
         }
 
-        $state = \SimpleSAML\Auth\State::loadState($relayState, 'core:LogoutTraditional');
+        $state = Auth\State::loadState($relayState, 'core:LogoutTraditional');
 
         if ($error === null) {
             Logger::info('Logged out of '.var_export($assocId, true).'.');
diff --git a/lib/SimpleSAML/Locale/Language.php b/lib/SimpleSAML/Locale/Language.php
index e8f06cf09875a05bfee64a5779acd3a4e5c4792b..31189db618c7febd7aaefd8a4e01ccdc5ed38ae6 100644
--- a/lib/SimpleSAML/Locale/Language.php
+++ b/lib/SimpleSAML/Locale/Language.php
@@ -10,7 +10,9 @@
 
 namespace SimpleSAML\Locale;
 
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Utils;
 
 class Language
 {
@@ -138,7 +140,7 @@ class Language
      *
      * @param \SimpleSAML\Configuration $configuration Configuration object
      */
-    public function __construct(\SimpleSAML\Configuration $configuration)
+    public function __construct(Configuration $configuration)
     {
         $this->configuration = $configuration;
         $this->availableLanguages = $this->getInstalledLanguages();
@@ -168,7 +170,7 @@ class Language
             if (array_key_exists($code, $this->language_names) && isset($this->language_names[$code])) {
                 $availableLanguages[] = $code;
             } else {
-                \SimpleSAML\Logger::error("Language \"$code\" not installed. Check config.");
+                Logger::error("Language \"$code\" not installed. Check config.");
             }
         }
         return $availableLanguages;
@@ -263,7 +265,7 @@ class Language
         if (array_key_exists($code, $this->language_names) && isset($this->language_names[$code])) {
             return $this->language_names[$code];
         }
-        \SimpleSAML\Logger::error("Name for language \"$code\" not found. Check config.");
+        Logger::error("Name for language \"$code\" not found. Check config.");
         return null;
     }
 
@@ -287,7 +289,7 @@ class Language
      */
     private function getHTTPLanguage()
     {
-        $languageScore = HTTP::getAcceptLanguage();
+        $languageScore = Utils\HTTP::getAcceptLanguage();
 
         // for now we only use the default language map. We may use a configurable language map in the future
         $languageMap = self::$defaultLanguageMap;
@@ -381,7 +383,7 @@ class Language
      */
     public static function getLanguageCookie()
     {
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $availableLanguages = $config->getArray('language.available', ['en']);
         $name = $config->getString('language.cookie.name', 'language');
 
@@ -408,7 +410,7 @@ class Language
         assert(is_string($language));
 
         $language = strtolower($language);
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $availableLanguages = $config->getArray('language.available', ['en']);
 
         if (!in_array($language, $availableLanguages, true) || headers_sent()) {
@@ -424,6 +426,6 @@ class Language
             'httponly' => ($config->getBoolean('language.cookie.httponly', false)),
         ];
 
-        HTTP::setCookie($name, $language, $params, false);
+        Utils\HTTP::setCookie($name, $language, $params, false);
     }
 }
diff --git a/lib/SimpleSAML/Locale/Localization.php b/lib/SimpleSAML/Locale/Localization.php
index c9c7e93a2f4f64fe339cc98bac239843e8954649..dd25eb131f8926f679be642cce0bb652d8ea06db 100644
--- a/lib/SimpleSAML/Locale/Localization.php
+++ b/lib/SimpleSAML/Locale/Localization.php
@@ -11,6 +11,8 @@ namespace SimpleSAML\Locale;
 
 use Gettext\Translations;
 use Gettext\Translator;
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
 
 class Localization
 {
@@ -90,7 +92,7 @@ class Localization
      *
      * @param \SimpleSAML\Configuration $configuration Configuration object
      */
-    public function __construct(\SimpleSAML\Configuration $configuration)
+    public function __construct(Configuration $configuration)
     {
         $this->configuration = $configuration;
         $this->localeDir = $this->configuration->resolvePath('locales');
@@ -154,7 +156,7 @@ class Localization
     public function addDomain($localeDir, $domain)
     {
         $this->localeDomainMap[$domain] = $localeDir;
-        \SimpleSAML\Logger::debug("Localization: load domain '$domain' at '$localeDir'");
+        Logger::debug("Localization: load domain '$domain' at '$localeDir'");
         $this->loadGettextGettextFromPO($domain);
     }
 
@@ -172,7 +174,7 @@ class Localization
         $langcode = $langcode[0];
         $localeDir = $this->localeDomainMap[$domain];
         $langPath = $localeDir.'/'.$langcode.'/LC_MESSAGES/';
-        \SimpleSAML\Logger::debug("Trying langpath for '$langcode' as '$langPath'");
+        Logger::debug("Trying langpath for '$langcode' as '$langPath'");
         if (is_dir($langPath) && is_readable($langPath)) {
             return $langPath;
         }
@@ -181,7 +183,7 @@ class Localization
         $alias = $this->language->getLanguageCodeAlias($langcode);
         if (isset($alias)) {
             $langPath = $localeDir.'/'.$alias.'/LC_MESSAGES/';
-            \SimpleSAML\Logger::debug("Trying langpath for alternative '$alias' as '$langPath'");
+            Logger::debug("Trying langpath for alternative '$alias' as '$langPath'");
             if (is_dir($langPath) && is_readable($langPath)) {
                 return $langPath;
             }
@@ -194,13 +196,13 @@ class Localization
             // Report that the localization for the preferred language is missing
             $error = "Localization not found for langcode '$langcode' at '$langPath', falling back to langcode '".
                 $defLangcode."'";
-            \SimpleSAML\Logger::error($_SERVER['PHP_SELF'].' - '.$error);
+            Logger::error($_SERVER['PHP_SELF'].' - '.$error);
             return $langPath;
         }
 
         // Locale for default language missing even, error out
         $error = "Localization directory missing/broken for langcode '$langcode' and domain '$domain'";
-        \SimpleSAML\Logger::critical($_SERVER['PHP_SELF'].' - '.$error);
+        Logger::critical($_SERVER['PHP_SELF'].' - '.$error);
         throw new \Exception($error);
     }
 
@@ -234,7 +236,7 @@ class Localization
             $langPath = $this->getLangPath($domain);
         } catch (\Exception $e) {
             $error = "Something went wrong when trying to get path to language file, cannot load domain '$domain'.";
-            \SimpleSAML\Logger::error($_SERVER['PHP_SELF'].' - '.$error);
+            Logger::error($_SERVER['PHP_SELF'].' - '.$error);
             if ($catchException) {
                 // bail out!
                 return;
@@ -249,7 +251,7 @@ class Localization
             $this->translator->loadTranslations($translations);
         } else {
             $error = "Localization file '$poFile' not found in '$langPath', falling back to default";
-            \SimpleSAML\Logger::error($_SERVER['PHP_SELF'].' - '.$error);
+            Logger::error($_SERVER['PHP_SELF'].' - '.$error);
         }
     }
 
@@ -277,7 +279,7 @@ class Localization
     private function setupL10N()
     {
         if ($this->i18nBackend === self::SSP_I18N_BACKEND) {
-            \SimpleSAML\Logger::debug("Localization: using old system");
+            Logger::debug("Localization: using old system");
             return;
         }
 
diff --git a/lib/SimpleSAML/Locale/Translate.php b/lib/SimpleSAML/Locale/Translate.php
index a5c0442ad2b23228b48dd00d4db5c80c1cb1aa07..7d7dfd177626c9a4ac85503050da8b0269a54690 100644
--- a/lib/SimpleSAML/Locale/Translate.php
+++ b/lib/SimpleSAML/Locale/Translate.php
@@ -10,6 +10,11 @@
 
 namespace SimpleSAML\Locale;
 
+use Gettext\BaseTranslator;
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+
 class Translate
 {
     /**
@@ -53,7 +58,7 @@ class Translate
      * @param \SimpleSAML\Configuration $configuration Configuration object
      * @param string|null               $defaultDictionary The default dictionary where tags will come from.
      */
-    public function __construct(\SimpleSAML\Configuration $configuration, $defaultDictionary = null)
+    public function __construct(Configuration $configuration, $defaultDictionary = null)
     {
         $this->configuration = $configuration;
         $this->language = new Language($configuration);
@@ -63,7 +68,7 @@ class Translate
             // for backwards compatibility - print warning
             $backtrace = debug_backtrace();
             $where = $backtrace[0]['file'].':'.$backtrace[0]['line'];
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Deprecated use of new SimpleSAML\Locale\Translate(...) at '.$where.
                 '. The last parameter is now a dictionary name, which should not end in ".php".'
             );
@@ -101,7 +106,7 @@ class Translate
             if ($sepPos !== false) {
                 $module = substr($name, 0, $sepPos);
                 $fileName = substr($name, $sepPos + 1);
-                $dictDir = \SimpleSAML\Module::getModuleDir($module).'/dictionaries/';
+                $dictDir = Module::getModuleDir($module).'/dictionaries/';
             } else {
                 $dictDir = $this->configuration->getPathValue('dictionarydir', 'dictionaries/');
                 $fileName = $name;
@@ -271,7 +276,7 @@ class Translate
         $backtrace = debug_backtrace();
         $where = $backtrace[0]['file'].':'.$backtrace[0]['line'];
         if (!$fallbackdefault) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Deprecated use of new SimpleSAML\Locale\Translate::t(...) at '.$where.
                 '. This parameter will go away, the fallback will become'.
                 ' identical to the $tag in 2.0.'
@@ -281,14 +286,14 @@ class Translate
             // TODO: remove this entire if for 2.0
 
             // old style call to t(...). Print warning to log
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Deprecated use of SimpleSAML\Locale\Translate::t(...) at '.$where.
                 '. Please update the code to use the new style of parameters.'
             );
 
             // for backwards compatibility
             if (!$replacements && ($this->getTag($tag) === null)) {
-                \SimpleSAML\Logger::warning(
+                Logger::warning(
                     'Code which uses $fallbackdefault === FALSE should be updated to use the getTag() method instead.'
                 );
                 return null;
@@ -299,7 +304,7 @@ class Translate
 
         if (is_array($tag)) {
             $tagData = $tag;
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Deprecated use of new SimpleSAML\Locale\Translate::t(...) at '.$where.
                 '. The $tag-parameter can only be a string in 2.0.'
             );
@@ -307,7 +312,7 @@ class Translate
             $tagData = $this->getTag($tag);
             if ($tagData === null) {
                 // tag not found
-                \SimpleSAML\Logger::info('Translate: Looking up ['.$tag.']: not translated at all.');
+                Logger::info('Translate: Looking up ['.$tag.']: not translated at all.');
                 return $this->getStringNotTranslated($tag, $fallbackdefault);
             }
         }
@@ -361,7 +366,7 @@ class Translate
             throw new \Exception("Inline translation should be string or array. Is ".gettype($translation)." now!");
         }
 
-        \SimpleSAML\Logger::debug('Translate: Adding inline language translation for tag ['.$tag.']');
+        Logger::debug('Translate: Adding inline language translation for tag ['.$tag.']');
         $this->langtext[$tag] = $translation;
     }
 
@@ -384,7 +389,7 @@ class Translate
         }
 
         $lang = $this->readDictionaryFile($filebase.$file);
-        \SimpleSAML\Logger::debug('Translate: Merging language array. Loading ['.$file.']');
+        Logger::debug('Translate: Merging language array. Loading ['.$file.']');
         $this->langtext = array_merge($this->langtext, $lang);
     }
 
@@ -404,7 +409,7 @@ class Translate
         $lang = json_decode($fileContent, true);
 
         if (empty($lang)) {
-            \SimpleSAML\Logger::error('Invalid dictionary definition file ['.$definitionFile.']');
+            Logger::error('Invalid dictionary definition file ['.$definitionFile.']');
             return [];
         }
 
@@ -452,7 +457,7 @@ class Translate
     {
         assert(is_string($filename));
 
-        \SimpleSAML\Logger::debug('Translate: Reading dictionary ['.$filename.']');
+        Logger::debug('Translate: Reading dictionary ['.$filename.']');
 
         $jsonFile = $filename.'.definition.json';
         if (file_exists($jsonFile)) {
@@ -464,7 +469,7 @@ class Translate
             return $this->readDictionaryPHP($filename);
         }
 
-        \SimpleSAML\Logger::error(
+        Logger::error(
             $_SERVER['PHP_SELF'].' - Translate: Could not find dictionary file at ['.$filename.']'
         );
         return [];
@@ -479,7 +484,7 @@ class Translate
      */
     public static function translateSingularGettext($original)
     {
-        $text = \Gettext\BaseTranslator::$current->gettext($original);
+        $text = BaseTranslator::$current->gettext($original);
 
         if (func_num_args() === 1) {
             return $text;
@@ -501,7 +506,7 @@ class Translate
      */
     public static function translatePluralGettext($original, $plural, $value)
     {
-        $text = \Gettext\BaseTranslator::$current->ngettext($original, $plural, $value);
+        $text = BaseTranslator::$current->ngettext($original, $plural, $value);
 
         if (func_num_args() === 3) {
             return $text;
@@ -538,10 +543,10 @@ class Translate
         }
 
         // we don't have a translation for the current language, load alternative priorities
-        $sspcfg = \SimpleSAML\Configuration::getInstance();
+        $sspcfg = Configuration::getInstance();
         $langcfg = $sspcfg->getConfigItem('language', null);
         $priorities = [];
-        if ($langcfg instanceof \SimpleSAML\Configuration) {
+        if ($langcfg instanceof Configuration) {
             $priorities = $langcfg->getArray('priorities', []);
         }
 
diff --git a/lib/SimpleSAML/Logger.php b/lib/SimpleSAML/Logger.php
index 696ce6fe57050085ab3e91bb991d3f373145889e..ba193eae843ecf83d1568aa07366cd3abefaace6 100644
--- a/lib/SimpleSAML/Logger.php
+++ b/lib/SimpleSAML/Logger.php
@@ -376,7 +376,7 @@ class Logger
 
         // register a shutdown handler if needed
         if (!self::$shutdownRegistered) {
-            register_shutdown_function(['SimpleSAML\Logger', 'flush']);
+            register_shutdown_function([self::class, 'flush']);
             self::$shutdownRegistered = true;
         }
     }
diff --git a/lib/SimpleSAML/Logger/ErrorLogLoggingHandler.php b/lib/SimpleSAML/Logger/ErrorLogLoggingHandler.php
index bde8bc75733383d35d270851b97ee202676b805a..07bfea093e2e7ec3bac7e7ac2e780008c7a5a7a5 100644
--- a/lib/SimpleSAML/Logger/ErrorLogLoggingHandler.php
+++ b/lib/SimpleSAML/Logger/ErrorLogLoggingHandler.php
@@ -2,6 +2,7 @@
 
 namespace SimpleSAML\Logger;
 
+use SimpleSAML\Configuration;
 use SimpleSAML\Logger;
 
 /**
@@ -43,7 +44,7 @@ class ErrorLogLoggingHandler implements LoggingHandlerInterface
      *
      * @param \SimpleSAML\Configuration $config The configuration object for this handler.
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         $this->processname = $config->getString('logging.processname', 'SimpleSAMLphp');
     }
diff --git a/lib/SimpleSAML/Logger/FileLoggingHandler.php b/lib/SimpleSAML/Logger/FileLoggingHandler.php
index 5a6923f9265051521bbea863e8d1d93cd625e447..a85307f6b7f15e2357f52eb742c6654f6d1c1d0d 100644
--- a/lib/SimpleSAML/Logger/FileLoggingHandler.php
+++ b/lib/SimpleSAML/Logger/FileLoggingHandler.php
@@ -2,7 +2,9 @@
 
 namespace SimpleSAML\Logger;
 
+use SimpleSAML\Configuration;
 use SimpleSAML\Logger;
+use SimpleSAML\Utils;
 
 /**
  * A logging handler that dumps logs to files.
@@ -48,7 +50,7 @@ class FileLoggingHandler implements LoggingHandlerInterface
      * Build a new logging handler based on files.
      * @param \SimpleSAML\Configuration $config
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         // get the metadata handler option from the configuration
         $this->logFile = $config->getPathValue('loggingdir', 'log/').
@@ -68,7 +70,7 @@ class FileLoggingHandler implements LoggingHandlerInterface
             }
         }
 
-        \SimpleSAML\Utils\Time::initTimezone();
+        Utils\Time::initTimezone();
     }
 
 
diff --git a/lib/SimpleSAML/Logger/LoggingHandlerInterface.php b/lib/SimpleSAML/Logger/LoggingHandlerInterface.php
index e3b46cf27705be1aac3835197b6b5519a85dbfde..3d00324e5e21b1e649f81e9eeffc6cd8d284f54a 100644
--- a/lib/SimpleSAML/Logger/LoggingHandlerInterface.php
+++ b/lib/SimpleSAML/Logger/LoggingHandlerInterface.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Logger;
 
+use SimpleSAML\Configuration;
+
 /**
  * The interface that must be implemented by any log handler.
  *
@@ -16,7 +18,7 @@ interface LoggingHandlerInterface
      *
      * @param \SimpleSAML\Configuration $config The configuration to use in this log handler.
      */
-    public function __construct(\SimpleSAML\Configuration $config);
+    public function __construct(Configuration $config);
 
 
     /**
diff --git a/lib/SimpleSAML/Logger/StandardErrorLoggingHandler.php b/lib/SimpleSAML/Logger/StandardErrorLoggingHandler.php
index f17e58ddc5e12fddab7c4933ebe72959769df098..ecc028bf0e0e301a13bb5f149100501c1d76403b 100644
--- a/lib/SimpleSAML/Logger/StandardErrorLoggingHandler.php
+++ b/lib/SimpleSAML/Logger/StandardErrorLoggingHandler.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Logger;
 
+use SimpleSAML\Configuration;
+
 /**
  * A logging handler that outputs all messages to standard error.
  *
@@ -17,7 +19,7 @@ class StandardErrorLoggingHandler extends FileLoggingHandler
      *
      * @param \SimpleSAML\Configuration $config
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         $this->processname = $config->getString('logging.processname', 'SimpleSAMLphp');
         $this->logFile = 'php://stderr';
diff --git a/lib/SimpleSAML/Logger/SyslogLoggingHandler.php b/lib/SimpleSAML/Logger/SyslogLoggingHandler.php
index fcbb157ffc554e94c9f99c52869fb0038a042282..a5cfa6bc0692809b46792163b52afcc8270a82ca 100644
--- a/lib/SimpleSAML/Logger/SyslogLoggingHandler.php
+++ b/lib/SimpleSAML/Logger/SyslogLoggingHandler.php
@@ -2,7 +2,8 @@
 
 namespace SimpleSAML\Logger;
 
-use SimpleSAML\Utils\System;
+use SimpleSAML\Configuration;
+use SimpleSAML\Utils;
 
 /**
  * A logger that sends messages to syslog.
@@ -24,14 +25,14 @@ class SyslogLoggingHandler implements LoggingHandlerInterface
      * Build a new logging handler based on syslog.
      * @param \SimpleSAML\Configuration $config
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         $facility = $config->getInteger('logging.facility', defined('LOG_LOCAL5') ? constant('LOG_LOCAL5') : LOG_USER);
 
         $processname = $config->getString('logging.processname', 'SimpleSAMLphp');
 
         // Setting facility to LOG_USER (only valid in Windows), enable log level rewrite on windows systems
-        if (System::getOS() === System::WINDOWS) {
+        if (Utils\System::getOS() === Utils\System::WINDOWS) {
             $this->isWindows = true;
             $facility = LOG_USER;
         }
diff --git a/lib/SimpleSAML/Memcache.php b/lib/SimpleSAML/Memcache.php
index bccf7be723c92830caf03eb93697b543d5390f55..0d4a11eded06d535a064f07d09f5f8edab44548a 100644
--- a/lib/SimpleSAML/Memcache.php
+++ b/lib/SimpleSAML/Memcache.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML;
 
+use SimpleSAML\Utils;
+
 /**
  * This file implements functions to read and write to a group of memcache
  * servers.
@@ -417,7 +419,7 @@ class Memcache
     {
         // get the configuration instance
         $config = Configuration::getInstance();
-        assert($config instanceof \SimpleSAML\Configuration);
+        assert($config instanceof Configuration);
 
         // get the expire-value from the configuration
         $expire = $config->getInteger('memcache_store.expires', 0);
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php
index a0ee3db680e55e1ac973f90b49e9d4f9a3b072a5..00b5674be01422386ac0c31a177f3a81a01ecf1c 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandler.php
@@ -2,8 +2,12 @@
 
 namespace SimpleSAML\Metadata;
 
+use SAML2\Constants;
 use SAML2\XML\saml\Issuer;
-use SimpleSAML\Utils\ClearableState;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Utils;
 
 /**
  * This file defines a class for metadata handling.
@@ -12,7 +16,7 @@ use SimpleSAML\Utils\ClearableState;
  * @package SimpleSAMLphp
  */
 
-class MetaDataStorageHandler implements ClearableState
+class MetaDataStorageHandler implements \SimpleSAML\Utils\ClearableState
 {
     /**
      * This static variable contains a reference to the current
@@ -56,7 +60,7 @@ class MetaDataStorageHandler implements ClearableState
      */
     protected function __construct()
     {
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
 
         $sourcesConfig = $config->getArray('metadata.sources', null);
 
@@ -98,14 +102,14 @@ class MetaDataStorageHandler implements ClearableState
         }
 
         // get the configuration
-        $config = \SimpleSAML\Configuration::getInstance();
-        assert($config instanceof \SimpleSAML\Configuration);
+        $config = Configuration::getInstance();
+        assert($config instanceof Configuration);
 
-        $baseurl = \SimpleSAML\Utils\HTTP::getSelfURLHost().$config->getBasePath();
+        $baseurl = Utils\HTTP::getSelfURLHost().$config->getBasePath();
 
         if ($set == 'saml20-sp-hosted') {
             if ($property === 'SingleLogoutServiceBinding') {
-                return \SAML2\Constants::BINDING_HTTP_REDIRECT;
+                return Constants::BINDING_HTTP_REDIRECT;
             }
         } elseif ($set == 'saml20-idp-hosted') {
             switch ($property) {
@@ -113,13 +117,13 @@ class MetaDataStorageHandler implements ClearableState
                     return $baseurl.'saml2/idp/SSOService.php';
 
                 case 'SingleSignOnServiceBinding':
-                    return \SAML2\Constants::BINDING_HTTP_REDIRECT;
+                    return Constants::BINDING_HTTP_REDIRECT;
 
                 case 'SingleLogoutService':
                     return $baseurl.'saml2/idp/SingleLogoutService.php';
 
                 case 'SingleLogoutServiceBinding':
-                    return \SAML2\Constants::BINDING_HTTP_REDIRECT;
+                    return Constants::BINDING_HTTP_REDIRECT;
             }
         } elseif ($set == 'shib13-idp-hosted') {
             if ($property === 'SingleSignOnService') {
@@ -152,9 +156,9 @@ class MetaDataStorageHandler implements ClearableState
                 if (array_key_exists('expire', $le)) {
                     if ($le['expire'] < time()) {
                         unset($srcList[$key]);
-                        \SimpleSAML\Logger::warning(
+                        Logger::warning(
                             "Dropping metadata entity ".var_export($key, true).", expired ".
-                            \SimpleSAML\Utils\Time::generateTimestamp($le['expire'])."."
+                            Utils\Time::generateTimestamp($le['expire'])."."
                         );
                     }
                 }
@@ -199,7 +203,7 @@ class MetaDataStorageHandler implements ClearableState
         assert(is_string($set));
 
         // first we look for the hostname/path combination
-        $currenthostwithpath = \SimpleSAML\Utils\HTTP::getSelfHostWithPath(); // sp.example.org/university
+        $currenthostwithpath = Utils\HTTP::getSelfHostWithPath(); // sp.example.org/university
 
         foreach ($this->sources as $source) {
             $index = $source->getEntityIdFromHostPath($currenthostwithpath, $set, $type);
@@ -209,7 +213,7 @@ class MetaDataStorageHandler implements ClearableState
         }
 
         // then we look for the hostname
-        $currenthost = \SimpleSAML\Utils\HTTP::getSelfHost(); // sp.example.org
+        $currenthost = Utils\HTTP::getSelfHost(); // sp.example.org
 
         foreach ($this->sources as $source) {
             $index = $source->getEntityIdFromHostPath($currenthost, $set, $type);
@@ -299,7 +303,7 @@ class MetaDataStorageHandler implements ClearableState
             }
         }
 
-        throw new \SimpleSAML\Error\MetadataNotFound($index);
+        throw new Error\MetadataNotFound($index);
     }
 
 
@@ -320,7 +324,7 @@ class MetaDataStorageHandler implements ClearableState
         assert(is_string($set));
 
         $metadata = $this->getMetaData($entityId, $set);
-        return \SimpleSAML\Configuration::loadFromArray($metadata, $set.'/'.var_export($entityId, true));
+        return Configuration::loadFromArray($metadata, $set.'/'.var_export($entityId, true));
     }
 
 
@@ -352,7 +356,7 @@ class MetaDataStorageHandler implements ClearableState
             if (sha1($remote_provider['entityid']) == $sha1) {
                 $remote_provider['metadata-set'] = $set;
 
-                return \SimpleSAML\Configuration::loadFromArray(
+                return Configuration::loadFromArray(
                     $remote_provider,
                     $set.'/'.var_export($remote_provider['entityid'], true)
                 );
@@ -362,6 +366,7 @@ class MetaDataStorageHandler implements ClearableState
         return null;
     }
 
+
     /**
      * Clear any metadata cached.
      * Allows for metadata configuration to be changed and reloaded during a given request. Most useful
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php
index de0fb88b0efc2f0d017b70a95be5a06179f819ef..f18ac585a548fef08a4ed2ddf8c77942095e6ba7 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerFlatFile.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Metadata;
 
+use SimpleSAML\Configuration;
+
 /**
  * This file defines a flat file metadata source.
  * Instantiation of session handler objects should be done through
@@ -44,7 +46,7 @@ class MetaDataStorageHandlerFlatFile extends MetaDataStorageSource
         assert(is_array($config));
 
         // get the configuration
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
 
         // find the path to the directory we should search for metadata in
         if (array_key_exists('directory', $config)) {
@@ -105,11 +107,11 @@ class MetaDataStorageHandlerFlatFile extends MetaDataStorageSource
             return $this->cachedMetadata[$set];
         }
 
+        /** @var array|null $metadataSet */
         $metadataSet = $this->load($set);
         if ($metadataSet === null) {
             $metadataSet = [];
         }
-        /** @var array $metadataSet */
 
         // add the entity id of an entry to each entry in the metadata
         foreach ($metadataSet as $entityId => &$entry) {
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php
index 4c26cec764fb36ee4b6ccf12f52b8fd961b2483e..408bfb243f1e575c8808f0e73103113971402fea 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerPdo.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Metadata;
 
+use SimpleSAML\Database;
+use SimpleSAML\Error;
+
 /**
  * Class for handling metadata files stored in a database.
  *
@@ -62,7 +65,7 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource
     {
         assert(is_array($config));
 
-        $this->db = \SimpleSAML\Database::getInstance();
+        $this->db = Database::getInstance();
     }
 
 
@@ -95,7 +98,7 @@ class MetaDataStorageHandlerPdo extends MetaDataStorageSource
             while ($d = $stmt->fetch()) {
                 $data = json_decode($d['entity_data'], true);
                 if ($data === null) {
-                    throw new \SimpleSAML\Error\Exception("Cannot decode metadata for entity '${d['entity_id']}'");
+                    throw new Error\Exception("Cannot decode metadata for entity '${d['entity_id']}'");
                 }
                 if (!array_key_exists('entityid', $data)) {
                     $data['entityid'] = $d['entity_id'];
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php
index fa57368561aa78726bfbfe527d227c966d024c76..0d7474e3dd7bfad84ce1f0247e0a94854d31320c 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerSerialize.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Metadata;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+
 /**
  * Class for handling metadata files in serialized format.
  *
@@ -37,9 +40,9 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
     {
         assert(is_array($config));
 
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
 
-        $cfgHelp = \SimpleSAML\Configuration::loadFromArray($config, 'serialize metadata source');
+        $cfgHelp = Configuration::loadFromArray($config, 'serialize metadata source');
 
         $this->directory = $cfgHelp->getString('directory');
 
@@ -78,7 +81,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
 
         $dh = @opendir($this->directory);
         if ($dh === false) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Serialize metadata handler: Unable to open directory: '.var_export($this->directory, true)
             );
             return $ret;
@@ -93,7 +96,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
             $path = $this->directory.'/'.$entry;
 
             if (!is_dir($path)) {
-                \SimpleSAML\Logger::warning(
+                Logger::warning(
                     'Serialize metadata handler: Metadata directory contained a file where only directories should '.
                     'exist: '.var_export($path, true)
                 );
@@ -130,7 +133,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
 
         $dh = @opendir($dir);
         if ($dh === false) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Serialize metadata handler: Unable to open directory: '.var_export($dir, true)
             );
             return $ret;
@@ -185,7 +188,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
         $data = @file_get_contents($filePath);
         if ($data === false) {
             $error = error_get_last();
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Error reading file '.$filePath.': '.$error['message']
             );
             return null;
@@ -193,7 +196,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
 
         $data = @unserialize($data);
         if ($data === false) {
-            \SimpleSAML\Logger::warning('Error unserializing file: '.$filePath);
+            Logger::warning('Error unserializing file: '.$filePath);
             return null;
         }
 
@@ -225,30 +228,30 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
 
         $dir = dirname($filePath);
         if (!is_dir($dir)) {
-            \SimpleSAML\Logger::info('Creating directory: '.$dir);
+            Logger::info('Creating directory: '.$dir);
             $res = @mkdir($dir, 0777, true);
             if ($res === false) {
                 $error = error_get_last();
-                \SimpleSAML\Logger::error('Failed to create directory '.$dir.': '.$error['message']);
+                Logger::error('Failed to create directory '.$dir.': '.$error['message']);
                 return false;
             }
         }
 
         $data = serialize($metadata);
 
-        \SimpleSAML\Logger::debug('Writing: '.$newPath);
+        Logger::debug('Writing: '.$newPath);
 
         $res = file_put_contents($newPath, $data);
         if ($res === false) {
             $error = error_get_last();
-            \SimpleSAML\Logger::error('Error saving file '.$newPath.': '.$error['message']);
+            Logger::error('Error saving file '.$newPath.': '.$error['message']);
             return false;
         }
 
         $res = rename($newPath, $filePath);
         if ($res === false) {
             $error = error_get_last();
-            \SimpleSAML\Logger::error('Error renaming '.$newPath.' to '.$filePath.': '.$error['message']);
+            Logger::error('Error renaming '.$newPath.' to '.$filePath.': '.$error['message']);
             return false;
         }
 
@@ -271,7 +274,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
         $filePath = $this->getMetadataPath($entityId, $set);
 
         if (!file_exists($filePath)) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Attempted to erase nonexistent metadata entry '.
                 var_export($entityId, true).' in set '.var_export($set, true).'.'
             );
@@ -281,7 +284,7 @@ class MetaDataStorageHandlerSerialize extends MetaDataStorageSource
         $res = unlink($filePath);
         if ($res === false) {
             $error = error_get_last();
-            \SimpleSAML\Logger::error(
+            Logger::error(
                 'Failed to delete file '.$filePath.
                 ': '.$error['message']
             );
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerXML.php b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerXML.php
index 9430781b6c1d02d2d6edbb451ec990183e8915f6..e47ddedf864932474cd0a4e9633bc3b513d5a697 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageHandlerXML.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageHandlerXML.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Metadata;
 
+use SimpleSAML\Configuration;
+
 /**
  * This class implements a metadata source which loads metadata from XML files.
  * The XML files should be in the SAML 2.0 metadata format.
@@ -12,7 +14,6 @@ namespace SimpleSAML\Metadata;
 
 class MetaDataStorageHandlerXML extends MetaDataStorageSource
 {
-
     /**
      * This variable contains an associative array with the parsed metadata.
      *
@@ -37,7 +38,7 @@ class MetaDataStorageHandlerXML extends MetaDataStorageSource
         $src = $srcXml = null;
         if (array_key_exists('file', $config)) {
             // get the configuration
-            $globalConfig = \SimpleSAML\Configuration::getInstance();
+            $globalConfig = Configuration::getInstance();
             $src = $globalConfig->resolvePath($config['file']);
         } elseif (array_key_exists('url', $config)) {
             $src = $config['url'];
diff --git a/lib/SimpleSAML/Metadata/MetaDataStorageSource.php b/lib/SimpleSAML/Metadata/MetaDataStorageSource.php
index e6cdb5d15942f769897293e5cb66255e89157e21..81ffd3b12ec190674bc2974ba6a45aeb4ef667a1 100644
--- a/lib/SimpleSAML/Metadata/MetaDataStorageSource.php
+++ b/lib/SimpleSAML/Metadata/MetaDataStorageSource.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Metadata;
 
+use SimpleSAML\Error;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
 /**
  * This abstract class defines an interface for metadata storage sources.
  *
@@ -82,13 +86,13 @@ abstract class MetaDataStorageSource
             default:
                 // metadata store from module
                 try {
-                    $className = \SimpleSAML\Module::resolveClass(
+                    $className = Module::resolveClass(
                         $type,
                         'MetadataStore',
                         '\SimpleSAML\Metadata\MetaDataStorageSource'
                     );
                 } catch (\Exception $e) {
-                    throw new \SimpleSAML\Error\CriticalConfigurationError(
+                    throw new Error\CriticalConfigurationError(
                         "Invalid 'type' for metadata source. Cannot find store '$type'.",
                         null
                     );
@@ -173,7 +177,6 @@ abstract class MetaDataStorageSource
      */
     public function getPreferredEntityIdFromCIDRhint($set, $ip, $type = 'entityid')
     {
-
         $metadataSet = $this->getMetadataSet($set);
 
         foreach ($metadataSet as $index => $entry) {
@@ -197,7 +200,7 @@ abstract class MetaDataStorageSource
             }
 
             foreach ($cidrHints as $hint_entry) {
-                if (\SimpleSAML\Utils\Net::ipCIDRcheck($hint_entry, $ip)) {
+                if (Utils\Net::ipCIDRcheck($hint_entry, $ip)) {
                     if ($type === 'entityid') {
                         return $entry['entityid'];
                     } else {
@@ -256,7 +259,7 @@ abstract class MetaDataStorageSource
         assert(is_array($metadataSet));
 
         // check for hostname
-        $currentHost = \SimpleSAML\Utils\HTTP::getSelfHost(); // sp.example.org
+        $currentHost = Utils\HTTP::getSelfHost(); // sp.example.org
 
         foreach ($metadataSet as $index => $entry) {
             // explicit index match
@@ -284,7 +287,7 @@ abstract class MetaDataStorageSource
         assert(is_string($set));
 
         // get the configuration
-        $baseUrl = \SimpleSAML\Utils\HTTP::getBaseURL();
+        $baseUrl = Utils\HTTP::getBaseURL();
 
         if ($set === 'saml20-idp-hosted') {
             return $baseUrl.'saml2/idp/metadata.php';
@@ -299,10 +302,10 @@ abstract class MetaDataStorageSource
             return $baseUrl.'shib13/sp/metadata.php';
         }
         else if ($set === 'wsfed-sp-hosted') {
-            return 'urn:federation:'.\SimpleSAML\Utils\HTTP::getSelfHost();
+            return 'urn:federation:'.Utils\HTTP::getSelfHost();
         }
         else if ($set === 'adfs-idp-hosted') {
-            return 'urn:federation:'.\SimpleSAML\Utils\HTTP::getSelfHost().':idp';
+            return 'urn:federation:'.Utils\HTTP::getSelfHost().':idp';
         }
         else {
             throw new \Exception('Can not generate dynamic EntityID for metadata of this type: ['.$set.']');
@@ -340,4 +343,4 @@ abstract class MetaDataStorageSource
 
         return $modifiedMetadataEntry;
     }
-}
\ No newline at end of file
+}
diff --git a/lib/SimpleSAML/Metadata/SAMLBuilder.php b/lib/SimpleSAML/Metadata/SAMLBuilder.php
index 733d802f731c4020dc0d0b78c51a9f30802e77f1..c8eb4af3978a727f5eb4b87708a03b834f945015 100644
--- a/lib/SimpleSAML/Metadata/SAMLBuilder.php
+++ b/lib/SimpleSAML/Metadata/SAMLBuilder.php
@@ -2,7 +2,30 @@
 
 namespace SimpleSAML\Metadata;
 
-use \SAML2\XML\md\EntityDescriptor;
+use SAML2\Constants;
+use SAML2\XML\md\AttributeAuthorityDescriptor;
+use SAML2\XML\md\AttributeConsumingService;
+use SAML2\XML\md\EndpointType;
+use SAML2\XML\md\EntityDescriptor;
+use SAML2\XML\md\IDPSSODescriptor;
+use SAML2\XML\md\IndexedEndpointType;
+use SAML2\XML\md\Organization;
+use SAML2\XML\md\RequestedAttribute;
+use SAML2\XML\md\RoleDescriptor;
+use SAML2\XML\md\SPSSODescriptor;
+use SAML2\XML\mdattr\EntityAttributes;
+use SAML2\XML\mdrpi\RegistrationInfo;
+use SAML2\XML\mdui\DiscoHints;
+use SAML2\XML\mdui\Keywords;
+use SAML2\XML\mdui\Logo;
+use SAML2\XML\mdui\UIInfo;
+use SAML2\XML\saml\Attribute;
+use SAML2\XML\saml\AttributeValue;
+use SAML2\XML\shibmd\Scope;
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Module\adfs\SAML2\XML\fed\SecurityTokenServiceType;
+use SimpleSAML\Utils;
 
 /**
  * Class for generating SAML 2.0 metadata from SimpleSAMLphp metadata arrays.
@@ -109,7 +132,7 @@ class SAMLBuilder
 
         $xml = $this->getEntityDescriptor();
         if ($formatted) {
-            \SimpleSAML\Utils\XML::formatDOMElement($xml);
+            Utils\XML::formatDOMElement($xml);
         }
 
         return $xml->ownerDocument->saveXML();
@@ -128,9 +151,9 @@ class SAMLBuilder
         assert(isset($metadata['entityid']));
         assert(isset($metadata['metadata-set']));
 
-        $metadata = \SimpleSAML\Configuration::loadFromArray($metadata, $metadata['entityid']);
+        $metadata = Configuration::loadFromArray($metadata, $metadata['entityid']);
         $defaultEndpoint = $metadata->getDefaultEndpoint('SingleSignOnService');
-        $e = new \SimpleSAML\Module\adfs\SAML2\XML\fed\SecurityTokenServiceType();
+        $e = new SecurityTokenServiceType();
         $e->setLocation($defaultEndpoint['Location']);
 
         $this->addCertificate($e, $metadata);
@@ -146,29 +169,29 @@ class SAMLBuilder
      * @param \SAML2\XML\md\RoleDescriptor $e Reference to the element where the Extensions element should be included.
      * @return void
      */
-    private function addExtensions(\SimpleSAML\Configuration $metadata, \SAML2\XML\md\RoleDescriptor $e)
+    private function addExtensions(Configuration $metadata, RoleDescriptor $e)
     {
         if ($metadata->hasValue('tags')) {
-            $a = new \SAML2\XML\saml\Attribute();
+            $a = new Attribute();
             $a->setName('tags');
             foreach ($metadata->getArray('tags') as $tag) {
-                $a->addAttributeValue(new \SAML2\XML\saml\AttributeValue($tag));
+                $a->addAttributeValue(new AttributeValue($tag));
             }
             $e->setExtensions(array_merge($e->getExtensions(), [$a]));
         }
 
         if ($metadata->hasValue('hint.cidr')) {
-            $a = new \SAML2\XML\saml\Attribute();
+            $a = new Attribute();
             $a->setName('hint.cidr');
             foreach ($metadata->getArray('hint.cidr') as $hint) {
-                $a->addAttributeValue(new \SAML2\XML\saml\AttributeValue($hint));
+                $a->addAttributeValue(new AttributeValue($hint));
             }
             $e->setExtensions(array_merge($e->getExtensions(), [$a]));
         }
 
         if ($metadata->hasValue('scope')) {
             foreach ($metadata->getArray('scope') as $scopetext) {
-                $s = new \SAML2\XML\shibmd\Scope();
+                $s = new Scope();
                 $s->setScope($scopetext);
                 // Check whether $ ^ ( ) * | \ are in a scope -> assume regex.
                 if (1 === preg_match('/[\$\^\)\(\*\|\\\\]/', $scopetext)) {
@@ -181,9 +204,9 @@ class SAMLBuilder
         }
 
         if ($metadata->hasValue('EntityAttributes')) {
-            $ea = new \SAML2\XML\mdattr\EntityAttributes();
+            $ea = new EntityAttributes();
             foreach ($metadata->getArray('EntityAttributes') as $attributeName => $attributeValues) {
-                $a = new \SAML2\XML\saml\Attribute();
+                $a = new Attribute();
                 $a->setName($attributeName);
                 $a->setNameFormat('urn:oasis:names:tc:SAML:2.0:attrname-format:uri');
 
@@ -191,12 +214,12 @@ class SAMLBuilder
                 if (preg_match('/^\{(.*?)\}(.*)$/', $attributeName, $matches)) {
                     $a->setName($matches[2]);
                     $nameFormat = $matches[1];
-                    if ($nameFormat !== \SAML2\Constants::NAMEFORMAT_UNSPECIFIED) {
+                    if ($nameFormat !== Constants::NAMEFORMAT_UNSPECIFIED) {
                         $a->setNameFormat($nameFormat);
                     }
                 }
                 foreach ($attributeValues as $attributeValue) {
-                    $a->addAttributeValue(new \SAML2\XML\saml\AttributeValue($attributeValue));
+                    $a->addAttributeValue(new AttributeValue($attributeValue));
                 }
                 $ea->addChildren($a);
             }
@@ -206,7 +229,7 @@ class SAMLBuilder
         }
 
         if ($metadata->hasValue('RegistrationInfo')) {
-            $ri = new \SAML2\XML\mdrpi\RegistrationInfo();
+            $ri = new RegistrationInfo();
             foreach ($metadata->getArray('RegistrationInfo') as $riName => $riValues) {
                 switch ($riName) {
                     case 'authority':
@@ -226,7 +249,7 @@ class SAMLBuilder
         }
 
         if ($metadata->hasValue('UIInfo')) {
-            $ui = new \SAML2\XML\mdui\UIInfo();
+            $ui = new UIInfo();
             foreach ($metadata->getArray('UIInfo') as $uiName => $uiValues) {
                 switch ($uiName) {
                     case 'DisplayName':
@@ -243,7 +266,7 @@ class SAMLBuilder
                         break;
                     case 'Keywords':
                         foreach ($uiValues as $lang => $keywords) {
-                            $uiItem = new \SAML2\XML\mdui\Keywords();
+                            $uiItem = new Keywords();
                             $uiItem->setLanguage($lang);
                             $uiItem->setKeywords($keywords);
                             $ui->addKeyword($uiItem);
@@ -251,7 +274,7 @@ class SAMLBuilder
                         break;
                     case 'Logo':
                         foreach ($uiValues as $logo) {
-                            $uiItem = new \SAML2\XML\mdui\Logo();
+                            $uiItem = new Logo();
                             $uiItem->setUrl($logo['url']);
                             $uiItem->setWidth($logo['width']);
                             $uiItem->setHeight($logo['height']);
@@ -267,7 +290,7 @@ class SAMLBuilder
         }
 
         if ($metadata->hasValue('DiscoHints')) {
-            $dh = new \SAML2\XML\mdui\DiscoHints();
+            $dh = new DiscoHints();
             foreach ($metadata->getArray('DiscoHints') as $dhName => $dhValues) {
                 switch ($dhName) {
                     case 'IPHint':
@@ -296,7 +319,7 @@ class SAMLBuilder
      */
     public function addOrganization(array $orgName, array $orgDisplayName, array $orgURL)
     {
-        $org = new \SAML2\XML\md\Organization();
+        $org = new Organization();
 
         $org->setOrganizationName($orgName);
         $org->setOrganizationDisplayName($orgDisplayName);
@@ -322,9 +345,9 @@ class SAMLBuilder
             return;
         }
 
-        $orgName = \SimpleSAML\Utils\Arrays::arrayize($metadata['OrganizationName'], 'en');
-        $orgDisplayName = \SimpleSAML\Utils\Arrays::arrayize($metadata['OrganizationDisplayName'], 'en');
-        $orgURL = \SimpleSAML\Utils\Arrays::arrayize($metadata['OrganizationURL'], 'en');
+        $orgName = Utils\Arrays::arrayize($metadata['OrganizationName'], 'en');
+        $orgDisplayName = Utils\Arrays::arrayize($metadata['OrganizationDisplayName'], 'en');
+        $orgURL = Utils\Arrays::arrayize($metadata['OrganizationURL'], 'en');
 
         $this->addOrganization($orgName, $orgDisplayName, $orgURL);
     }
@@ -347,7 +370,7 @@ class SAMLBuilder
 
         foreach ($endpoints as &$ep) {
             if ($indexed) {
-                $t = new \SAML2\XML\md\IndexedEndpointType();
+                $t = new IndexedEndpointType();
                 if (!isset($ep['index'])) {
                     // Find the maximum index
                     $maxIndex = -1;
@@ -366,7 +389,7 @@ class SAMLBuilder
 
                 $t->setIndex($ep['index']);
             } else {
-                $t = new \SAML2\XML\md\EndpointType();
+                $t = new EndpointType();
             }
 
             $t->setBinding($ep['Binding']);
@@ -376,9 +399,9 @@ class SAMLBuilder
             }
             if (isset($ep['hoksso:ProtocolBinding'])) {
                 $t->setAttributeNS(
-                    \SAML2\Constants::NS_HOK,
+                    Constants::NS_HOK,
                     'hoksso:ProtocolBinding',
-                    \SAML2\Constants::BINDING_HTTP_REDIRECT
+                    Constants::BINDING_HTTP_REDIRECT
                 );
             }
 
@@ -397,8 +420,8 @@ class SAMLBuilder
      * @return void
      */
     private function addAttributeConsumingService(
-        \SAML2\XML\md\SPSSODescriptor $spDesc,
-        \SimpleSAML\Configuration $metadata
+        SPSSODescriptor $spDesc,
+        Configuration $metadata
     ) {
         $attributes = $metadata->getArray('attributes', []);
         $name = $metadata->getLocalizedString('name', null);
@@ -414,7 +437,7 @@ class SAMLBuilder
          * Add an AttributeConsumingService element with information as name and description and list
          * of requested attributes
          */
-        $attributeconsumer = new \SAML2\XML\md\AttributeConsumingService();
+        $attributeconsumer = new AttributeConsumingService();
 
         $attributeconsumer->setIndex($metadata->getInteger('attributes.index', 0));
 
@@ -425,14 +448,14 @@ class SAMLBuilder
         $attributeconsumer->setServiceName($name);
         $attributeconsumer->setServiceDescription($metadata->getLocalizedString('description', []));
 
-        $nameFormat = $metadata->getString('attributes.NameFormat', \SAML2\Constants::NAMEFORMAT_UNSPECIFIED);
+        $nameFormat = $metadata->getString('attributes.NameFormat', Constants::NAMEFORMAT_UNSPECIFIED);
         foreach ($attributes as $friendlyName => $attribute) {
-            $t = new \SAML2\XML\md\RequestedAttribute();
+            $t = new RequestedAttribute();
             $t->setName($attribute);
             if (!is_int($friendlyName)) {
                 $t->setFriendlyName($friendlyName);
             }
-            if ($nameFormat !== \SAML2\Constants::NAMEFORMAT_UNSPECIFIED) {
+            if ($nameFormat !== Constants::NAMEFORMAT_UNSPECIFIED) {
                 $t->setNameFormat($nameFormat);
             }
             if (in_array($attribute, $attributesrequired, true)) {
@@ -476,7 +499,7 @@ class SAMLBuilder
                 $this->addAttributeAuthority($metadata);
                 break;
             default:
-                \SimpleSAML\Logger::warning('Unable to generate metadata for unknown type \''.$set.'\'.');
+                Logger::warning('Unable to generate metadata for unknown type \''.$set.'\'.');
         }
     }
 
@@ -488,16 +511,16 @@ class SAMLBuilder
      * @param array $protocols The protocols supported. Defaults to \SAML2\Constants::NS_SAMLP.
      * @return void
      */
-    public function addMetadataSP20($metadata, $protocols = [\SAML2\Constants::NS_SAMLP])
+    public function addMetadataSP20($metadata, $protocols = [Constants::NS_SAMLP])
     {
         assert(is_array($metadata));
         assert(is_array($protocols));
         assert(isset($metadata['entityid']));
         assert(isset($metadata['metadata-set']));
 
-        $metadata = \SimpleSAML\Configuration::loadFromArray($metadata, $metadata['entityid']);
+        $metadata = Configuration::loadFromArray($metadata, $metadata['entityid']);
 
-        $e = new \SAML2\XML\md\SPSSODescriptor();
+        $e = new SPSSODescriptor();
         $e->setProtocolSupportEnumeration($protocols);
 
         if ($metadata->hasValue('saml20.sign.assertion')) {
@@ -521,7 +544,7 @@ class SAMLBuilder
         $endpoints = $metadata->getEndpoints('AssertionConsumerService');
         foreach ($metadata->getArrayizeString('AssertionConsumerService.artifact', []) as $acs) {
             $endpoints[] = [
-                'Binding'  => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact',
+                'Binding'  => Constants::BINDING_HTTP_ARTIFACT,
                 'Location' => $acs,
             ];
         }
@@ -533,7 +556,7 @@ class SAMLBuilder
 
         foreach ($metadata->getArray('contacts', []) as $contact) {
             if (array_key_exists('contactType', $contact) && array_key_exists('emailAddress', $contact)) {
-                $this->addContact($contact['contactType'], \SimpleSAML\Utils\Config\Metadata::getContact($contact));
+                $this->addContact($contact['contactType'], Utils\Config\Metadata::getContact($contact));
             }
         }
     }
@@ -551,10 +574,10 @@ class SAMLBuilder
         assert(isset($metadata['entityid']));
         assert(isset($metadata['metadata-set']));
 
-        $metadata = \SimpleSAML\Configuration::loadFromArray($metadata, $metadata['entityid']);
+        $metadata = Configuration::loadFromArray($metadata, $metadata['entityid']);
 
-        $e = new \SAML2\XML\md\IDPSSODescriptor();
-        $e->setProtocolSupportEnumeration(array_merge($e->getProtocolSupportEnumeration(), ['urn:oasis:names:tc:SAML:2.0:protocol']));
+        $e = new IDPSSODescriptor();
+        $e->setProtocolSupportEnumeration(array_merge($e->getProtocolSupportEnumeration(), [Constants::NS_SAMLP]));
 
         if ($metadata->hasValue('sign.authnrequest')) {
             $e->setWantAuthnRequestsSigned($metadata->getBoolean('sign.authnrequest'));
@@ -583,7 +606,7 @@ class SAMLBuilder
 
         foreach ($metadata->getArray('contacts', []) as $contact) {
             if (array_key_exists('contactType', $contact) && array_key_exists('emailAddress', $contact)) {
-                $this->addContact($contact['contactType'], \SimpleSAML\Utils\Config\Metadata::getContact($contact));
+                $this->addContact($contact['contactType'], Utils\Config\Metadata::getContact($contact));
             }
         }
     }
@@ -601,13 +624,15 @@ class SAMLBuilder
         assert(isset($metadata['entityid']));
         assert(isset($metadata['metadata-set']));
 
-        $metadata = \SimpleSAML\Configuration::loadFromArray($metadata, $metadata['entityid']);
+        $metadata = Configuration::loadFromArray($metadata, $metadata['entityid']);
 
-        $e = new \SAML2\XML\md\SPSSODescriptor();
-        $e->setProtocolSupportEnumeration(array_merge(
+        $e = new SPSSODescriptor();
+        $e->setProtocolSupportEnumeration(
+            array_merge(
                 $e->getProtocolSupportEnumeration(),
                 ['urn:oasis:names:tc:SAML:1.1:protocol']
-        ));
+            )
+        );
 
         $this->addCertificate($e, $metadata);
 
@@ -640,9 +665,9 @@ class SAMLBuilder
         assert(isset($metadata['entityid']));
         assert(isset($metadata['metadata-set']));
 
-        $metadata = \SimpleSAML\Configuration::loadFromArray($metadata, $metadata['entityid']);
+        $metadata = Configuration::loadFromArray($metadata, $metadata['entityid']);
 
-        $e = new \SAML2\XML\md\IDPSSODescriptor();
+        $e = new IDPSSODescriptor();
         $e->setProtocolSupportEnumeration(
             array_merge($e->getProtocolSupportEnumeration(), [
                 'urn:oasis:names:tc:SAML:1.1:protocol',
@@ -673,10 +698,10 @@ class SAMLBuilder
         assert(isset($metadata['entityid']));
         assert(isset($metadata['metadata-set']));
 
-        $metadata = \SimpleSAML\Configuration::loadFromArray($metadata, $metadata['entityid']);
+        $metadata = Configuration::loadFromArray($metadata, $metadata['entityid']);
 
-        $e = new \SAML2\XML\md\AttributeAuthorityDescriptor();
-        $e->setProtocolSupportEnumeration($metadata->getArray('protocols', [\SAML2\Constants::NS_SAMLP]));
+        $e = new AttributeAuthorityDescriptor();
+        $e->setProtocolSupportEnumeration($metadata->getArray('protocols', [Constants::NS_SAMLP]));
 
         $this->addExtensions($metadata, $e);
         $this->addCertificate($e, $metadata);
@@ -714,7 +739,7 @@ class SAMLBuilder
         assert(in_array($type, ['technical', 'support', 'administrative', 'billing', 'other'], true));
 
         // TODO: remove this check as soon as getContact() is called always before calling this function
-        $details = \SimpleSAML\Utils\Config\Metadata::getContact($details);
+        $details = Utils\Config\Metadata::getContact($details);
 
         $e = new \SAML2\XML\md\ContactPerson();
         $e->setContactType($type);
@@ -765,7 +790,7 @@ class SAMLBuilder
      * @param string                      $x509data The certificate data.
      * @return void
      */
-    private function addX509KeyDescriptor(\SAML2\XML\md\RoleDescriptor $rd, $use, $x509data)
+    private function addX509KeyDescriptor(RoleDescriptor $rd, $use, $x509data)
     {
         assert(in_array($use, ['encryption', 'signing'], true));
         assert(is_string($x509data));
@@ -785,7 +810,7 @@ class SAMLBuilder
      * @param \SimpleSAML\Configuration    $metadata The metadata of the entity.
      * @return void
      */
-    private function addCertificate(\SAML2\XML\md\RoleDescriptor $rd, \SimpleSAML\Configuration $metadata)
+    private function addCertificate(RoleDescriptor $rd, Configuration $metadata)
     {
         $keys = $metadata->getPublicKeys();
         foreach ($keys as $key) {
diff --git a/lib/SimpleSAML/Metadata/SAMLParser.php b/lib/SimpleSAML/Metadata/SAMLParser.php
index f330b82d4057af8fcf81927d9f9db1ebfd75bcda..d18c6d176e41a114841d7b148f5d828aede50612 100644
--- a/lib/SimpleSAML/Metadata/SAMLParser.php
+++ b/lib/SimpleSAML/Metadata/SAMLParser.php
@@ -2,8 +2,37 @@
 
 namespace SimpleSAML\Metadata;
 
+use DOMDocument;
 use RobRichards\XMLSecLibs\XMLSecurityDSig;
 use RobRichards\XMLSecLibs\XMLSecurityKey;
+use SAML2\Constants;
+use SAML2\DOMDocumentFactory;
+use SAML2\XML\Chunk;
+use SAML2\XML\ds\X509Certificate;
+use SAML2\XML\ds\X509Data;
+use SAML2\XML\md\AttributeAuthorityDescriptor;
+use SAML2\XML\md\AttributeConsumingService;
+use SAML2\XML\md\ContactPerson;
+use SAML2\XML\md\EndpointType;
+use SAML2\XML\md\EntityDescriptor;
+use SAML2\XML\md\EntitiesDescriptor;
+use SAML2\XML\md\IDPSSODescriptor;
+use SAML2\XML\md\IndexedEndpointType;
+use SAML2\XML\md\KeyDescriptor;
+use SAML2\XML\md\Organization;
+use SAML2\XML\md\RoleDescriptor;
+use SAML2\XML\md\SPSSODescriptor;
+use SAML2\XML\md\SSODescriptorType;
+use SAML2\XML\mdattr\EntityAttributes;
+use SAML2\XML\mdrpi\RegistrationInfo;
+use SAML2\XML\mdui\DiscoHints;
+use SAML2\XML\mdui\Keywords;
+use SAML2\XML\mdui\Logo;
+use SAML2\XML\mdui\UIInfo;
+use SAML2\XML\saml\Attribute;
+use SAML2\XML\shibmd\Scope;
+use SimpleSAML\Logger;
+use SimpleSAML\Utils;
 
 /**
  * This is class for parsing of SAML 1.x and SAML 2.0 metadata.
@@ -35,7 +64,7 @@ class SAMLParser
      * @var string[]
      */
     private static $SAML20Protocols = [
-        'urn:oasis:names:tc:SAML:2.0:protocol',
+        Constants::NS_SAMLP,
     ];
 
     /**
@@ -142,6 +171,7 @@ class SAMLParser
      */
     private $entityDescriptor;
 
+
     /**
      * This is the constructor for the SAMLParser class.
      *
@@ -152,7 +182,7 @@ class SAMLParser
      * @param array                         $parentExtensions An optional array of extensions from the parent element.
      */
     private function __construct(
-        \SAML2\XML\md\EntityDescriptor $entityElement,
+        EntityDescriptor $entityElement,
         $maxExpireTime,
         array $validators = [],
         array $parentExtensions = []
@@ -181,11 +211,11 @@ class SAMLParser
 
         // look over the RoleDescriptors
         foreach ($entityElement->getRoleDescriptor() as $child) {
-            if ($child instanceof \SAML2\XML\md\SPSSODescriptor) {
+            if ($child instanceof SPSSODescriptor) {
                 $this->processSPSSODescriptor($child, $expireTime);
-            } elseif ($child instanceof \SAML2\XML\md\IDPSSODescriptor) {
+            } elseif ($child instanceof IDPSSODescriptor) {
                 $this->processIDPSSODescriptor($child, $expireTime);
-            } elseif ($child instanceof \SAML2\XML\md\AttributeAuthorityDescriptor) {
+            } elseif ($child instanceof AttributeAuthorityDescriptor) {
                 $this->processAttributeAuthorityDescriptor($child, $expireTime);
             }
         }
@@ -213,10 +243,10 @@ class SAMLParser
     public static function parseFile($file)
     {
         /** @var string $data */
-        $data = \SimpleSAML\Utils\HTTP::fetch($file);
+        $data = Utils\HTTP::fetch($file);
 
         try {
-            $doc = \SAML2\DOMDocumentFactory::fromString($data);
+            $doc = DOMDocumentFactory::fromString($data);
         } catch (\Exception $e) {
             throw new \Exception('Failed to read XML from file: '.$file);
         }
@@ -236,7 +266,7 @@ class SAMLParser
     public static function parseString($metadata)
     {
         try {
-            $doc = \SAML2\DOMDocumentFactory::fromString($metadata);
+            $doc = DOMDocumentFactory::fromString($metadata);
         } catch (\Exception $e) {
             throw new \Exception('Failed to parse XML string.');
         }
@@ -254,7 +284,7 @@ class SAMLParser
      */
     public static function parseDocument($document)
     {
-        assert($document instanceof \DOMDocument);
+        assert($document instanceof DOMDocument);
 
         $entityElement = self::findEntityDescriptor($document);
 
@@ -272,7 +302,7 @@ class SAMLParser
      */
     public static function parseElement($entityElement)
     {
-        assert($entityElement instanceof \SAML2\XML\md\EntityDescriptor);
+        assert($entityElement instanceof EntityDescriptor);
         return new SAMLParser($entityElement, null, []);
     }
 
@@ -295,10 +325,10 @@ class SAMLParser
         }
 
         /** @var string $data */
-        $data = \SimpleSAML\Utils\HTTP::fetch($file);
+        $data = Utils\HTTP::fetch($file);
 
         try {
-            $doc = \SAML2\DOMDocumentFactory::fromString($data);
+            $doc = DOMDocumentFactory::fromString($data);
         } catch (\Exception $e) {
             throw new \Exception('Failed to read XML from file: '.$file);
         }
@@ -325,7 +355,7 @@ class SAMLParser
     public static function parseDescriptorsString($string)
     {
         try {
-            $doc = \SAML2\DOMDocumentFactory::fromString($string);
+            $doc = DOMDocumentFactory::fromString($string);
         } catch (\Exception $e) {
             throw new \Exception('Failed to parse XML string.');
         }
@@ -351,10 +381,10 @@ class SAMLParser
             throw new \Exception('Document was empty.');
         }
 
-        if (\SimpleSAML\Utils\XML::isDOMNodeOfType($element, 'EntityDescriptor', '@md') === true) {
-            return self::processDescriptorsElement(new \SAML2\XML\md\EntityDescriptor($element));
-        } elseif (\SimpleSAML\Utils\XML::isDOMNodeOfType($element, 'EntitiesDescriptor', '@md') === true) {
-            return self::processDescriptorsElement(new \SAML2\XML\md\EntitiesDescriptor($element));
+        if (Utils\XML::isDOMNodeOfType($element, 'EntityDescriptor', '@md') === true) {
+            return self::processDescriptorsElement(new EntityDescriptor($element));
+        } elseif (Utils\XML::isDOMNodeOfType($element, 'EntitiesDescriptor', '@md') === true) {
+            return self::processDescriptorsElement(new EntitiesDescriptor($element));
         } else {
             throw new \Exception('Unexpected root node: ['.$element->namespaceURI.']:'.$element->localName);
         }
@@ -381,14 +411,14 @@ class SAMLParser
     ) {
         assert($maxExpireTime === null || is_int($maxExpireTime));
 
-        if ($element instanceof \SAML2\XML\md\EntityDescriptor) {
+        if ($element instanceof EntityDescriptor) {
             $ret = new SAMLParser($element, $maxExpireTime, $validators, $parentExtensions);
             $ret = [$ret->getEntityId() => $ret];
             /** @var SAMLParser[] $ret */
             return $ret;
         }
 
-        assert($element instanceof \SAML2\XML\md\EntitiesDescriptor);
+        assert($element instanceof EntitiesDescriptor);
 
         $extensions = self::processExtensions($element, $parentExtensions);
         $expTime = self::getExpireTime($element, $maxExpireTime);
@@ -501,7 +531,7 @@ class SAMLParser
             $metadata['EntityAttributes'] = $this->entityAttributes;
 
             // check for entity categories
-            if (\SimpleSAML\Utils\Config\Metadata::isHiddenFromDiscovery($metadata)) {
+            if (Utils\Config\Metadata::isHiddenFromDiscovery($metadata)) {
                 $metadata['hide.from.discovery'] = true;
             }
         }
@@ -689,7 +719,7 @@ class SAMLParser
 
         // find the NameIDFormat. This may not exist
         if (count($spd['nameIDFormats']) > 0) {
-            // SimpleSAMLphp currently only supports a single NameIDFormat pr. SP. We use the first one
+            // SimpleSAMLphp currently only supports a single NameIDFormat per SP. We use the first one
             $ret['NameIDFormat'] = $spd['nameIDFormats'][0];
         }
 
@@ -841,7 +871,7 @@ class SAMLParser
      *
      * @return array An associative array with metadata we have extracted from this element.
      */
-    private static function parseRoleDescriptorType(\SAML2\XML\md\RoleDescriptor $element, $expireTime)
+    private static function parseRoleDescriptorType(RoleDescriptor $element, $expireTime)
     {
         assert($expireTime === null || is_int($expireTime));
 
@@ -892,7 +922,7 @@ class SAMLParser
      *
      * @return array An associative array with metadata we have extracted from this element.
      */
-    private static function parseSSODescriptor(\SAML2\XML\md\SSODescriptorType $element, $expireTime)
+    private static function parseSSODescriptor(SSODescriptorType $element, $expireTime)
     {
         assert($expireTime === null || is_int($expireTime));
 
@@ -920,7 +950,7 @@ class SAMLParser
      *                             NULL if unknown.
      * @return void
      */
-    private function processSPSSODescriptor(\SAML2\XML\md\SPSSODescriptor $element, $expireTime)
+    private function processSPSSODescriptor(SPSSODescriptor $element, $expireTime)
     {
         assert($expireTime === null || is_int($expireTime));
 
@@ -957,7 +987,7 @@ class SAMLParser
      *                             NULL if unknown.
      * @return void
      */
-    private function processIDPSSODescriptor(\SAML2\XML\md\IDPSSODescriptor $element, $expireTime)
+    private function processIDPSSODescriptor(IDPSSODescriptor $element, $expireTime)
     {
         assert($expireTime === null || is_int($expireTime));
 
@@ -985,7 +1015,7 @@ class SAMLParser
      * @return void
      */
     private function processAttributeAuthorityDescriptor(
-        \SAML2\XML\md\AttributeAuthorityDescriptor $element,
+        AttributeAuthorityDescriptor $element,
         $expireTime
     ) {
         assert($expireTime === null || is_int($expireTime));
@@ -1023,35 +1053,35 @@ class SAMLParser
         ];
 
         // Some extensions may get inherited from a parent element
-        if (($element instanceof \SAML2\XML\md\EntityDescriptor || $element instanceof \SAML2\XML\md\EntitiesDescriptor)
+        if (($element instanceof EntityDescriptor || $element instanceof EntitiesDescriptor)
                 && !empty($parentExtensions['RegistrationInfo'])) {
             $ret['RegistrationInfo'] = $parentExtensions['RegistrationInfo'];
         }
 
         foreach ($element->getExtensions() as $e) {
-            if ($e instanceof \SAML2\XML\shibmd\Scope) {
+            if ($e instanceof Scope) {
                 $ret['scope'][] = $e->getScope();
                 continue;
             }
 
             // Entity Attributes are only allowed at entity level extensions and not at RoleDescriptor level
-            if ($element instanceof \SAML2\XML\md\EntityDescriptor ||
-                $element instanceof \SAML2\XML\md\EntitiesDescriptor) {
-                if ($e instanceof \SAML2\XML\mdrpi\RegistrationInfo) {
+            if ($element instanceof EntityDescriptor ||
+                $element instanceof EntitiesDescriptor) {
+                if ($e instanceof RegistrationInfo) {
                     // Registration Authority cannot be overridden (warn only if override attempts to change the value)
                     if (isset($ret['RegistrationInfo']['registrationAuthority'])
                         && $ret['RegistrationInfo']['registrationAuthority'] !== $e->getRegistrationAuthority()) {
-                        \SimpleSAML\Logger::warning('Invalid attempt to override registrationAuthority \''.
+                        Logger::warning('Invalid attempt to override registrationAuthority \''.
                             $ret['RegistrationInfo']['registrationAuthority']."' with '{$e->getRegistrationAuthority()}'");
                     } else {
                         $ret['RegistrationInfo']['registrationAuthority'] = $e->getRegistrationAuthority();
                     }
                 }
-                if ($e instanceof \SAML2\XML\mdattr\EntityAttributes && !empty($e->getChildren())) {
+                if ($e instanceof EntityAttributes && !empty($e->getChildren())) {
                     foreach ($e->getChildren() as $attr) {
                         // only saml:Attribute are currently supported here. The specifications also allows
                         // saml:Assertions, which more complex processing
-                        if ($attr instanceof \SAML2\XML\saml\Attribute) {
+                        if ($attr instanceof Attribute) {
                             $attrName = $attr->getName();
                             $attrNameFormat = $attr->getNameFormat();
                             $attrValue = $attr->getAttributeValue();
@@ -1063,8 +1093,8 @@ class SAMLParser
                             // attribute names that is not URI is prefixed as this: '{nameformat}name'
                             $name = $attrName;
                             if ($attrNameFormat === null) {
-                                $name = '{'.\SAML2\Constants::NAMEFORMAT_UNSPECIFIED.'}'.$attr->getName();
-                            } elseif ($attrNameFormat !== 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri') {
+                                $name = '{'.Constants::NAMEFORMAT_UNSPECIFIED.'}'.$attr->getName();
+                            } elseif ($attrNameFormat !== Constants::NAMEFORMAT_URI) {
                                 $name = '{'.$attrNameFormat.'}'.$attrName;
                             }
 
@@ -1080,8 +1110,8 @@ class SAMLParser
             }
 
             // UIInfo elements are only allowed at RoleDescriptor level extensions
-            if ($element instanceof \SAML2\XML\md\RoleDescriptor) {
-                if ($e instanceof \SAML2\XML\mdui\UIInfo) {
+            if ($element instanceof RoleDescriptor) {
+                if ($e instanceof UIInfo) {
                     $ret['UIInfo']['DisplayName'] = $e->getDisplayName();
                     $ret['UIInfo']['Description'] = $e->getDescription();
                     $ret['UIInfo']['InformationURL'] = $e->getInformationURL();
@@ -1097,7 +1127,7 @@ class SAMLParser
                         $ret['UIInfo']['Keywords'][$uiItem->getLanguage()] = $uiItem->getKeywords();
                     }
                     foreach ($e->getLogo() as $uiItem) {
-                        if (!($uiItem instanceof \SAML2\XML\mdui\Logo)
+                        if (!($uiItem instanceof Logo)
                             || ($uiItem->getUrl() === null)
                             || ($uiItem->getHeight() === null)
                             || ($uiItem->getWidth() === null)
@@ -1118,25 +1148,25 @@ class SAMLParser
             }
 
             // DiscoHints elements are only allowed at IDPSSODescriptor level extensions
-            if ($element instanceof \SAML2\XML\md\IDPSSODescriptor) {
-                if ($e instanceof \SAML2\XML\mdui\DiscoHints) {
+            if ($element instanceof IDPSSODescriptor) {
+                if ($e instanceof DiscoHints) {
                     $ret['DiscoHints']['IPHint'] = $e->getIPHint();
                     $ret['DiscoHints']['DomainHint'] = $e->getDomainHint();
                     $ret['DiscoHints']['GeolocationHint'] = $e->getGeolocationHint();
                 }
             }
 
-            if (!($e instanceof \SAML2\XML\Chunk)) {
+            if (!($e instanceof Chunk)) {
                 continue;
             }
 
-            if ($e->getLocalName() === 'Attribute' && $e->getNamespaceURI() === \SAML2\Constants::NS_SAML) {
+            if ($e->getLocalName() === 'Attribute' && $e->getNamespaceURI() === Constants::NS_SAML) {
                 $attribute = $e->getXML();
 
                 $name = $attribute->getAttribute('Name');
                 $values = array_map(
                     ['\SimpleSAML\Utils\XML', 'getDOMText'],
-                    \SimpleSAML\Utils\XML::getDOMChildren($attribute, 'AttributeValue', '@saml2')
+                    Utils\XML::getDOMChildren($attribute, 'AttributeValue', '@saml2')
                 );
 
                 if ($name === 'tags') {
@@ -1158,7 +1188,7 @@ class SAMLParser
      * @param \SAML2\XML\md\Organization $element The Organization element.
      * @return void
      */
-    private function processOrganization(\SAML2\XML\md\Organization $element)
+    private function processOrganization(Organization $element)
     {
         $this->organizationName = $element->getOrganizationName();
         $this->organizationDisplayName = $element->getOrganizationDisplayName();
@@ -1172,7 +1202,7 @@ class SAMLParser
      * @param \SAML2\XML\md\ContactPerson $element The ContactPerson element.
      * @return void
      */
-    private function processContactPerson(\SAML2\XML\md\ContactPerson $element)
+    private function processContactPerson(ContactPerson $element)
     {
         $contactPerson = [];
         if ($element->getContactType() !== '') {
@@ -1206,7 +1236,7 @@ class SAMLParser
      * @param array $sp The array with the SP's metadata.
      * @return void
      */
-    private static function parseAttributeConsumerService(\SAML2\XML\md\AttributeConsumingService $element, &$sp)
+    private static function parseAttributeConsumerService(AttributeConsumingService $element, &$sp)
     {
         assert(is_array($sp));
 
@@ -1227,13 +1257,13 @@ class SAMLParser
             if ($child->getNameFormat() !== null) {
                 $attrformat = $child->getNameFormat();
             } else {
-                $attrformat = \SAML2\Constants::NAMEFORMAT_UNSPECIFIED;
+                $attrformat = Constants::NAMEFORMAT_UNSPECIFIED;
             }
 
             if ($format === null) {
                 $format = $attrformat;
             } elseif ($format !== $attrformat) {
-                $format = \SAML2\Constants::NAMEFORMAT_UNSPECIFIED;
+                $format = Constants::NAMEFORMAT_UNSPECIFIED;
             }
         }
 
@@ -1245,7 +1275,7 @@ class SAMLParser
             unset($sp['attributes.required']);
         }
 
-        if ($format !== \SAML2\Constants::NAMEFORMAT_UNSPECIFIED && $format !== null) {
+        if ($format !== Constants::NAMEFORMAT_UNSPECIFIED && $format !== null) {
             $sp['attributes.NameFormat'] = $format;
         }
     }
@@ -1265,7 +1295,7 @@ class SAMLParser
      *
      * @return array An associative array with the data we have extracted from the element.
      */
-    private static function parseGenericEndpoint(\SAML2\XML\md\EndpointType $element)
+    private static function parseGenericEndpoint(EndpointType $element)
     {
         $ep = [];
 
@@ -1276,7 +1306,7 @@ class SAMLParser
             $ep['ResponseLocation'] = $element->getResponseLocation();
         }
 
-        if ($element instanceof \SAML2\XML\md\IndexedEndpointType) {
+        if ($element instanceof IndexedEndpointType) {
             $ep['index'] = $element->getIndex();
 
             if ($element->getIsDefault() !== null) {
@@ -1315,7 +1345,7 @@ class SAMLParser
      *
      * @return array|null An associative array describing the key, or null if this is an unsupported key.
      */
-    private static function parseKeyDescriptor(\SAML2\XML\md\KeyDescriptor $kd)
+    private static function parseKeyDescriptor(KeyDescriptor $kd)
     {
         $r = [];
 
@@ -1333,9 +1363,9 @@ class SAMLParser
         $keyInfo = $kd->getKeyInfo();
 
         foreach ($keyInfo->getInfo() as $i) {
-            if ($i instanceof \SAML2\XML\ds\X509Data) {
+            if ($i instanceof X509Data) {
                 foreach ($i->getData() as $d) {
-                    if ($d instanceof \SAML2\XML\ds\X509Certificate) {
+                    if ($d instanceof X509Certificate) {
                         $r['type'] = 'X509Certificate';
                         $r['X509Certificate'] = $d->getCertificate();
                         return $r;
@@ -1409,7 +1439,7 @@ class SAMLParser
      */
     private static function findEntityDescriptor($doc)
     {
-        assert($doc instanceof \DOMDocument);
+        assert($doc instanceof DOMDocument);
 
         // find the EntityDescriptor DOMElement. This should be the first (and only) child of the DOMDocument
         $ed = $doc->documentElement;
@@ -1418,11 +1448,11 @@ class SAMLParser
             throw new \Exception('Failed to load SAML metadata from empty XML document.');
         }
 
-        if (\SimpleSAML\Utils\XML::isDOMNodeOfType($ed, 'EntityDescriptor', '@md') === false) {
+        if (Utils\XML::isDOMNodeOfType($ed, 'EntityDescriptor', '@md') === false) {
             throw new \Exception('Expected first element in the metadata document to be an EntityDescriptor element.');
         }
 
-        return new \SAML2\XML\md\EntityDescriptor($ed);
+        return new EntityDescriptor($ed);
     }
 
 
@@ -1439,7 +1469,7 @@ class SAMLParser
     {
         foreach ($certificates as $cert) {
             assert(is_string($cert));
-            $certFile = \SimpleSAML\Utils\Config::getCertPath($cert);
+            $certFile = Utils\Config::getCertPath($cert);
             if (!file_exists($certFile)) {
                 throw new \Exception(
                     'Could not find certificate file ['.$certFile.'], which is needed to validate signature'
@@ -1459,7 +1489,7 @@ class SAMLParser
                 }
             }
         }
-        \SimpleSAML\Logger::debug('Could not validate signature');
+        Logger::debug('Could not validate signature');
         return false;
     }
 
@@ -1522,7 +1552,7 @@ class SAMLParser
                 }
             }
         }
-        \SimpleSAML\Logger::debug('Fingerprint was ['.$fingerprint.'] not one of ['.join(', ', $candidates).']');
+        Logger::debug('Fingerprint was ['.$fingerprint.'] not one of ['.join(', ', $candidates).']');
         return false;
     }
 }
diff --git a/lib/SimpleSAML/Metadata/Signer.php b/lib/SimpleSAML/Metadata/Signer.php
index ecb95441f6479a93f2d0f7cd602eabb45fd4821a..b149fdd9e359d2820e0ddd7f66b8117151963741 100644
--- a/lib/SimpleSAML/Metadata/Signer.php
+++ b/lib/SimpleSAML/Metadata/Signer.php
@@ -4,6 +4,10 @@ namespace SimpleSAML\Metadata;
 
 use RobRichards\XMLSecLibs\XMLSecurityKey;
 use RobRichards\XMLSecLibs\XMLSecurityDSig;
+use SAML2\DOMDocumentFactory;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Utils;
 
 /**
  * This class implements a helper function for signing of metadata.
@@ -163,7 +167,7 @@ class Signer
         // configure the algorithm to use
         if (array_key_exists('metadata.sign.algorithm', $entityMetadata)) {
             if (!is_string($entityMetadata['metadata.sign.algorithm'])) {
-                throw new \SimpleSAML\Error\CriticalConfigurationError(
+                throw new Error\CriticalConfigurationError(
                     "Invalid value for the 'metadata.sign.algorithm' configuration option for the ".$type.
                     "'".$entityMetadata['entityid']."'. This option has restricted values"
                 );
@@ -181,7 +185,7 @@ class Signer
         ];
 
         if (!in_array($alg, $supported_algs, true)) {
-            throw new \SimpleSAML\Error\CriticalConfigurationError("Unknown signature algorithm '$alg'");
+            throw new Error\CriticalConfigurationError("Unknown signature algorithm '$alg'");
         }
 
         switch ($alg) {
@@ -217,7 +221,7 @@ class Signer
      */
     public static function sign($metadataString, $entityMetadata, $type)
     {
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
 
         // check if metadata signing is enabled
         if (!self::isMetadataSigningEnabled($config, $entityMetadata, $type)) {
@@ -227,7 +231,7 @@ class Signer
         // find the key & certificate which should be used to sign the metadata
         $keyCertFiles = self::findKeyCert($config, $entityMetadata, $type);
 
-        $keyFile = \SimpleSAML\Utils\Config::getCertPath($keyCertFiles['privatekey']);
+        $keyFile = Utils\Config::getCertPath($keyCertFiles['privatekey']);
         if (!file_exists($keyFile)) {
             throw new \Exception(
                 'Could not find private key file ['.$keyFile.'], which is needed to sign the metadata'
@@ -235,7 +239,7 @@ class Signer
         }
         $keyData = file_get_contents($keyFile);
 
-        $certFile = \SimpleSAML\Utils\Config::getCertPath($keyCertFiles['certificate']);
+        $certFile = Utils\Config::getCertPath($keyCertFiles['certificate']);
         if (!file_exists($certFile)) {
             throw new \Exception(
                 'Could not find certificate file ['.$certFile.'], which is needed to sign the metadata'
@@ -246,7 +250,7 @@ class Signer
 
         // convert the metadata to a DOM tree
         try {
-            $xml = \SAML2\DOMDocumentFactory::fromString($metadataString);
+            $xml = DOMDocumentFactory::fromString($metadataString);
         } catch (\Exception $e) {
             throw new \Exception('Error parsing self-generated metadata.');
         }
diff --git a/lib/SimpleSAML/Metadata/Sources/MDQ.php b/lib/SimpleSAML/Metadata/Sources/MDQ.php
index 1f141657be9631a62597c2916c7fad85a23341df..bd47dfb093fb4d76ef3b863a8cac5b18f9211de8 100644
--- a/lib/SimpleSAML/Metadata/Sources/MDQ.php
+++ b/lib/SimpleSAML/Metadata/Sources/MDQ.php
@@ -3,8 +3,10 @@
 namespace SimpleSAML\Metadata\Sources;
 
 use RobRichards\XMLSecLibs\XMLSecurityDSig;
+use SimpleSAML\Configuration;
 use SimpleSAML\Logger;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Metadata\SAMLParser;
+use SimpleSAML\Utils;
 
 /**
  * This class implements SAML Metadata Query Protocol
@@ -86,7 +88,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource
         }
 
         if (array_key_exists('cachedir', $config)) {
-            $globalConfig = \SimpleSAML\Configuration::getInstance();
+            $globalConfig = Configuration::getInstance();
             $this->cacheDir = $globalConfig->resolvePath($config['cachedir']);
         } else {
             $this->cacheDir = null;
@@ -229,7 +231,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource
      * @return array|NULL  The associative array with the metadata, or NULL if no metadata for
      *                     the given set was found.
      */
-    private static function getParsedSet(\SimpleSAML\Metadata\SAMLParser $entity, $set)
+    private static function getParsedSet(SAMLParser $entity, $set)
     {
         assert(is_string($set));
 
@@ -304,7 +306,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource
 
         Logger::debug(__CLASS__.': downloading metadata for "'.$index.'" from ['.$mdq_url.']');
         try {
-            $xmldata = HTTP::fetch($mdq_url);
+            $xmldata = Utils\HTTP::fetch($mdq_url);
         } catch (\Exception $e) {
             // Avoid propagating the exception, make sure we can handle the error later
             $xmldata = false;
@@ -318,7 +320,7 @@ class MDQ extends \SimpleSAML\Metadata\MetaDataStorageSource
         }
 
         /** @var string $xmldata */
-        $entity = \SimpleSAML\Metadata\SAMLParser::parseString($xmldata);
+        $entity = SAMLParser::parseString($xmldata);
         Logger::debug(__CLASS__.': completed parsing of ['.$mdq_url.']');
 
         if ($this->validateFingerprint !== null) {
diff --git a/lib/SimpleSAML/Module.php b/lib/SimpleSAML/Module.php
index 40c664d55d20ac9b7d703dedd3338530db9cabfa..e0bf063a5c4f59b7da97ed64927f250333936786 100644
--- a/lib/SimpleSAML/Module.php
+++ b/lib/SimpleSAML/Module.php
@@ -2,11 +2,15 @@
 
 namespace SimpleSAML;
 
+use SimpleSAML\HTTP\Router;
+use SimpleSAML\Utils;
+use Symfony\Component\Config\Exception\FileLocatorFileNotFoundException;
 use Symfony\Component\HttpFoundation\BinaryFileResponse;
 use Symfony\Component\HttpFoundation\RedirectResponse;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpFoundation\ResponseHeaderBag;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
 
 /**
  * Helper class for accessing information about modules.
@@ -18,7 +22,6 @@ use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  */
 class Module
 {
-
     /**
      * Index pages: file names to attempt when accessing directories.
      *
@@ -166,12 +169,12 @@ class Module
 
         $config = Configuration::getInstance();
         if ($config->getBoolean('usenewui', false) === true) {
-            $router = new HTTP\Router($module);
+            $router = new Router($module);
             try {
                 return $router->process();
-            } catch (\Symfony\Component\Config\Exception\FileLocatorFileNotFoundException $e) {
+            } catch (FileLocatorFileNotFoundException $e) {
                 // no routes configured for this module, fall back to the old system
-            } catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
+            } catch (NotFoundHttpException $e) {
                 // this module has been migrated, but the route wasn't found
             }
         }
@@ -308,7 +311,7 @@ class Module
             !file_exists($moduleDir.'/default-enable') &&
             !file_exists($moduleDir.'/default-disable')
         ) {
-            \SimpleSAML\Logger::error("Missing default-enable or default-disable file for the module $module");
+            Logger::error("Missing default-enable or default-disable file for the module $module");
         }
 
         if (file_exists($moduleDir.'/enable')) {
@@ -517,7 +520,7 @@ class Module
             require_once(self::$module_info[$module]['hooks'][$hook]['file']);
 
             if (!is_callable(self::$module_info[$module]['hooks'][$hook]['func'])) {
-                throw new \SimpleSAML\Error\Exception('Invalid hook \''.$hook.'\' for module \''.$module.'\'.');
+                throw new Error\Exception('Invalid hook \''.$hook.'\' for module \''.$module.'\'.');
             }
 
             $fn = self::$module_info[$module]['hooks'][$hook]['func'];
diff --git a/lib/SimpleSAML/Module/ControllerResolver.php b/lib/SimpleSAML/Module/ControllerResolver.php
index 85d39744362857f9a8ce3faff8d8b368736453b6..633b7d861d8f1a09018b709f02aaea665f5217d3 100644
--- a/lib/SimpleSAML/Module/ControllerResolver.php
+++ b/lib/SimpleSAML/Module/ControllerResolver.php
@@ -33,7 +33,6 @@ use Symfony\Component\Routing\RouteCollection;
  */
 class ControllerResolver extends SymfonyControllerResolver implements ArgumentResolverInterface
 {
-
     /** @var ArgumentMetadataFactory */
     protected $argFactory;
 
@@ -137,7 +136,7 @@ class ControllerResolver extends SymfonyControllerResolver implements ArgumentRe
 
         /** @var ArgumentMetadata $argMeta */
         foreach ($metadata as $argMeta) {
-            if ($argMeta->getType() === 'Symfony\Component\HttpFoundation\Request') {
+            if ($argMeta->getType() === Request::class) {
                 // add request argument
                 $args[] = $request;
                 continue;
diff --git a/lib/SimpleSAML/Session.php b/lib/SimpleSAML/Session.php
index 062382c9cdfee0c887f12cb2845707bdd693b33b..816934a6e9b7a59dc3bcad96b721142d5e153725 100644
--- a/lib/SimpleSAML/Session.php
+++ b/lib/SimpleSAML/Session.php
@@ -2,7 +2,9 @@
 
 namespace SimpleSAML;
 
+use SAML2\XML\saml\AttributeValue;
 use SimpleSAML\Error;
+use SimpleSAML\Utils;
 
 /**
  * The Session class holds information about a user session, and everything attached to it.
@@ -643,7 +645,7 @@ class Session implements \Serializable, Utils\ClearableState
                 }
 
                 // create an AttributeValue object and save it to 'RawAttributes', using same attribute name and index
-                $attrval = new \SAML2\XML\saml\AttributeValue($value->item(0)->parentNode);
+                $attrval = new AttributeValue($value->item(0)->parentNode);
                 $data['RawAttributes'][$attribute][$idx] = $attrval;
             }
         }
diff --git a/lib/SimpleSAML/SessionHandlerCookie.php b/lib/SimpleSAML/SessionHandlerCookie.php
index 04ff7c0bb0142f4e2d6031af1848c45b60b0dca3..556105f2e830f2d6986cf8514e934cc113b60bf8 100644
--- a/lib/SimpleSAML/SessionHandlerCookie.php
+++ b/lib/SimpleSAML/SessionHandlerCookie.php
@@ -13,7 +13,7 @@
 
 namespace SimpleSAML;
 
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Utils;
 
 abstract class SessionHandlerCookie extends SessionHandler
 {
@@ -167,6 +167,6 @@ abstract class SessionHandlerCookie extends SessionHandler
             $params = $this->getCookieParams();
         }
 
-        HTTP::setCookie($sessionName, $sessionID, $params, true);
+        Utils\HTTP::setCookie($sessionName, $sessionID, $params, true);
     }
 }
diff --git a/lib/SimpleSAML/SessionHandlerPHP.php b/lib/SimpleSAML/SessionHandlerPHP.php
index a67e032428836f3982f5cb68d33771b1fe370a8d..da573a2df47f80f5befaf5849272d63ebb3394a0 100644
--- a/lib/SimpleSAML/SessionHandlerPHP.php
+++ b/lib/SimpleSAML/SessionHandlerPHP.php
@@ -11,8 +11,8 @@
 
 namespace SimpleSAML;
 
-use SimpleSAML\Error\CannotSetCookie;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Error;
+use SimpleSAML\Utils;
 
 class SessionHandlerPHP extends SessionHandler
 {
@@ -147,13 +147,13 @@ class SessionHandlerPHP extends SessionHandler
             $sid_bits_per_char = (int) ini_get('session.sid_bits_per_character');
 
             if (($sid_length * $sid_bits_per_char) < 128) {
-                \SimpleSAML\Logger::warning("Unsafe defaults used for sessionId generation!");
+                Logger::warning("Unsafe defaults used for sessionId generation!");
             }
             $sessionId = session_create_id();
         } else {
             $sessionId = bin2hex(openssl_random_pseudo_bytes(16));
         }
-        \SimpleSAML\Session::createSession($sessionId);
+        Session::createSession($sessionId);
         return $sessionId;
     }
 
@@ -175,8 +175,8 @@ class SessionHandlerPHP extends SessionHandler
 
         $session_cookie_params = session_get_cookie_params();
 
-        if ($session_cookie_params['secure'] && !HTTP::isHTTPS()) {
-            throw new \SimpleSAML\Error\Exception('Session start with secure cookie not allowed on http.');
+        if ($session_cookie_params['secure'] && !Utils\HTTP::isHTTPS()) {
+            throw new Error\Exception('Session start with secure cookie not allowed on http.');
         }
 
         @session_start();
@@ -226,13 +226,13 @@ class SessionHandlerPHP extends SessionHandler
                 // session not initiated with getCookieSessionId(), start session without setting cookie
                 $ret = ini_set('session.use_cookies', '0');
                 if ($ret === false) {
-                    throw new \SimpleSAML\Error\Exception('Disabling PHP option session.use_cookies failed.');
+                    throw new Error\Exception('Disabling PHP option session.use_cookies failed.');
                 }
 
                 session_id($sessionId);
                 @session_start();
             } elseif ($sessionId !== session_id()) {
-                throw new \SimpleSAML\Error\Exception('Cannot load PHP session with a specific ID.');
+                throw new Error\Exception('Cannot load PHP session with a specific ID.');
             }
         } elseif (session_id() === '') {
             $this->getCookieSessionId();
@@ -282,7 +282,7 @@ class SessionHandlerPHP extends SessionHandler
         $ret = parent::getCookieParams();
 
         if ($config->hasValue('session.phpsession.limitedpath') && $config->hasValue('session.cookie.path')) {
-            throw new \SimpleSAML\Error\Exception(
+            throw new Error\Exception(
                 'You cannot set both the session.phpsession.limitedpath and session.cookie.path options.'
             );
         } elseif ($config->hasValue('session.phpsession.limitedpath')) {
@@ -314,17 +314,17 @@ class SessionHandlerPHP extends SessionHandler
             $cookieParams = session_get_cookie_params();
         }
 
-        if ($cookieParams['secure'] && !HTTP::isHTTPS()) {
-            throw new CannotSetCookie(
+        if ($cookieParams['secure'] && !Utils\HTTP::isHTTPS()) {
+            throw new Error\CannotSetCookie(
                 'Setting secure cookie on plain HTTP is not allowed.',
-                CannotSetCookie::SECURE_COOKIE
+                Error\CannotSetCookie::SECURE_COOKIE
             );
         }
 
         if (headers_sent()) {
-            throw new CannotSetCookie(
+            throw new Error\CannotSetCookie(
                 'Headers already sent.',
-                CannotSetCookie::HEADERS_SENT
+                Error\CannotSetCookie::HEADERS_SENT
             );
         }
 
diff --git a/lib/SimpleSAML/Stats.php b/lib/SimpleSAML/Stats.php
index 8c77b0da8eba6a2a9611af698e67a6b04a6f153a..3a75fc357ad42cea2eef6bae8b951aaff57a5873 100644
--- a/lib/SimpleSAML/Stats.php
+++ b/lib/SimpleSAML/Stats.php
@@ -38,7 +38,7 @@ class Stats
     private static function createOutput(\SimpleSAML\Configuration $config)
     {
         $cls = $config->getString('class');
-        $cls = \SimpleSAML\Module::resolveClass($cls, 'Stats\Output', '\SimpleSAML\Stats\Output');
+        $cls = Module::resolveClass($cls, 'Stats\Output', '\SimpleSAML\Stats\Output');
 
         $output = new $cls($config);
         return $output;
@@ -53,7 +53,7 @@ class Stats
     private static function initOutputs()
     {
 
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $outputCfgs = $config->getConfigList('statistics.out', []);
 
         self::$outputs = [];
diff --git a/lib/SimpleSAML/Stats/Output.php b/lib/SimpleSAML/Stats/Output.php
index a4a05ed44b0f318d9ec339fc9ac1d6687b10b160..0790f6ac5033b09f7054b6cfa6644dd06e26142d 100644
--- a/lib/SimpleSAML/Stats/Output.php
+++ b/lib/SimpleSAML/Stats/Output.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Stats;
 
+use SimpleSAML\Configuration;
+
 /**
  * Interface for statistics outputs.
  *
@@ -15,7 +17,7 @@ abstract class Output
      *
      * @param \SimpleSAML\Configuration $config The configuration for this output.
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         // do nothing by default
     }
diff --git a/lib/SimpleSAML/Store.php b/lib/SimpleSAML/Store.php
index 70fca6c395745af92203389d07a065e0de30f3b6..46c9dba127081af443071963d3feaacdf27cccaf 100644
--- a/lib/SimpleSAML/Store.php
+++ b/lib/SimpleSAML/Store.php
@@ -2,7 +2,7 @@
 
 namespace SimpleSAML;
 
-use SimpleSAML\Error\CriticalConfigurationError;
+use SimpleSAML\Error;
 
 /**
  * Base class for data stores.
@@ -58,7 +58,7 @@ abstract class Store implements Utils\ClearableState
                 } catch (\Exception $e) {
                     $c = $config->toArray();
                     $c['store.type'] = 'phpsession';
-                    throw new CriticalConfigurationError(
+                    throw new Error\CriticalConfigurationError(
                         "Invalid 'store.type' configuration option. Cannot find store '$storeType'.",
                         null,
                         $c
diff --git a/lib/SimpleSAML/Store/Memcache.php b/lib/SimpleSAML/Store/Memcache.php
index 01739072e49a8785f6fde2e833ec6f1dfafb07d8..515ca953046f209264252dd080c34478a87da9b9 100644
--- a/lib/SimpleSAML/Store/Memcache.php
+++ b/lib/SimpleSAML/Store/Memcache.php
@@ -2,8 +2,8 @@
 
 namespace SimpleSAML\Store;
 
-use \SimpleSAML\Configuration;
-use \SimpleSAML\Store;
+use SimpleSAML\Configuration;
+use SimpleSAML\Store;
 
 /**
  * A memcache based data store.
diff --git a/lib/SimpleSAML/Store/Redis.php b/lib/SimpleSAML/Store/Redis.php
index 53c27f4549c333c95953f61b7f2e168e37c7c20e..3a8a410fea3b001ba5bacb36917b17d5459639a8 100644
--- a/lib/SimpleSAML/Store/Redis.php
+++ b/lib/SimpleSAML/Store/Redis.php
@@ -2,8 +2,10 @@
 
 namespace SimpleSAML\Store;
 
-use \SimpleSAML\Configuration;
-use \SimpleSAML\Store;
+use Predis\Client;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Store;
 
 /**
  * A data store using Redis to keep the data.
@@ -21,10 +23,10 @@ class Redis extends Store
      */
     public function __construct($redis = null)
     {
-        assert($redis === null || is_subclass_of($redis, 'Predis\\Client'));
+        assert($redis === null || is_subclass_of($redis, Client::class));
 
-        if (!class_exists('\Predis\Client')) {
-            throw new \SimpleSAML\Error\CriticalConfigurationError('predis/predis is not available.');
+        if (!class_exists(Client::class)) {
+            throw new Error\CriticalConfigurationError('predis/predis is not available.');
         }
 
         if ($redis === null) {
@@ -35,7 +37,7 @@ class Redis extends Store
             $prefix = $config->getString('store.redis.prefix', 'SimpleSAMLphp');
             $password = $config->getString('store.redis.password', '');
 
-            $redis = new \Predis\Client(
+            $redis = new Client(
                 [
                     'scheme' => 'tcp',
                     'host' => $host,
@@ -50,6 +52,7 @@ class Redis extends Store
         $this->redis = $redis;
     }
 
+
     /**
      * Deconstruct the Redis data store.
      */
@@ -60,6 +63,7 @@ class Redis extends Store
         }
     }
 
+
     /**
      * Retrieve a value from the data store.
      *
@@ -82,6 +86,7 @@ class Redis extends Store
         return unserialize($result);
     }
 
+
     /**
      * Save a value in the data store.
      *
@@ -107,6 +112,7 @@ class Redis extends Store
         }
     }
 
+
     /**
      * Delete an entry from the data store.
      *
diff --git a/lib/SimpleSAML/Store/SQL.php b/lib/SimpleSAML/Store/SQL.php
index 175d15c67f2aae9b5756fdda44df0f9c20b5a825..44599b9f9e4419248c05e6f96c879f2256feef95 100644
--- a/lib/SimpleSAML/Store/SQL.php
+++ b/lib/SimpleSAML/Store/SQL.php
@@ -2,9 +2,11 @@
 
 namespace SimpleSAML\Store;
 
-use \SimpleSAML\Configuration;
-use \SimpleSAML\Logger;
-use \SimpleSAML\Store;
+use PDO;
+use PDOException;
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Store;
 
 /**
  * A data store using a RDBMS to keep the data.
@@ -58,13 +60,13 @@ class SQL extends Store
         $options = $config->getArray('store.sql.options', null);
         $this->prefix = $config->getString('store.sql.prefix', 'simpleSAMLphp');
         try {
-            $this->pdo = new \PDO($dsn, $username, $password, $options);
-        } catch (\PDOException $e) {
+            $this->pdo = new PDO($dsn, $username, $password, $options);
+        } catch (PDOException $e) {
             throw new \Exception("Database error: ".$e->getMessage());
         }
-        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
+        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
-        $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
+        $this->driver = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
 
         if ($this->driver === 'mysql') {
             $this->pdo->exec('SET time_zone = "+00:00"');
@@ -85,7 +87,7 @@ class SQL extends Store
 
         try {
             $fetchTableVersion = $this->pdo->query('SELECT _name, _version FROM '.$this->prefix.'_tableVersion');
-        } catch (\PDOException $e) {
+        } catch (PDOException $e) {
             $this->pdo->exec(
                 'CREATE TABLE '.$this->prefix.
                 '_tableVersion (_name VARCHAR(30) NOT NULL UNIQUE, _version INTEGER NOT NULL)'
@@ -93,7 +95,7 @@ class SQL extends Store
             return;
         }
 
-        while (($row = $fetchTableVersion->fetch(\PDO::FETCH_ASSOC)) !== false) {
+        while (($row = $fetchTableVersion->fetch(PDO::FETCH_ASSOC)) !== false) {
             $this->tableVersions[$row['_name']] = (int) $row['_version'];
         }
     }
@@ -239,7 +241,7 @@ class SQL extends Store
         try {
             $insertQuery->execute($data);
             return;
-        } catch (\PDOException $e) {
+        } catch (PDOException $e) {
             $ecode = (string) $e->getCode();
             switch ($ecode) {
                 case '23505': // PostgreSQL
@@ -308,7 +310,7 @@ class SQL extends Store
         $query = $this->pdo->prepare($query);
         $query->execute($params);
 
-        $row = $query->fetch(\PDO::FETCH_ASSOC);
+        $row = $query->fetch(PDO::FETCH_ASSOC);
         if ($row === false) {
             return null;
         }
diff --git a/lib/SimpleSAML/Utils/Attributes.php b/lib/SimpleSAML/Utils/Attributes.php
index 88c87f1aa26a271f0f473062ace38c1c22029c07..c84f86b3e300f3b1dcd99b3fca7d7f356c2db9e1 100644
--- a/lib/SimpleSAML/Utils/Attributes.php
+++ b/lib/SimpleSAML/Utils/Attributes.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Utils;
 
+use SimpleSAML\Error;
+
 /**
  * Attribute-related utility methods.
  *
@@ -39,7 +41,7 @@ class Attributes
         }
 
         if (!array_key_exists($expected, $attributes)) {
-            throw new \SimpleSAML\Error\Exception("No such attribute '".$expected."' found.");
+            throw new Error\Exception("No such attribute '".$expected."' found.");
         }
         $attribute = $attributes[$expected];
 
@@ -48,7 +50,7 @@ class Attributes
         }
 
         if (count($attribute) === 0) {
-            throw new \SimpleSAML\Error\Exception("Empty attribute '".$expected."'.'");
+            throw new Error\Exception("Empty attribute '".$expected."'.'");
         } elseif (count($attribute) > 1) {
             if ($allow_multiple === false) {
                 throw new \SimpleSAML\Error\Exception(
diff --git a/lib/SimpleSAML/Utils/Auth.php b/lib/SimpleSAML/Utils/Auth.php
index 61d49b6e919409d83229ea958c91e1fc3ef0f51b..48cfcb16fcbf48de33b1d98e6d52713bf541f191 100644
--- a/lib/SimpleSAML/Utils/Auth.php
+++ b/lib/SimpleSAML/Utils/Auth.php
@@ -2,7 +2,10 @@
 
 namespace SimpleSAML\Utils;
 
+use SimpleSAML\Auth as Authentication;
+use SimpleSAML\Error;
 use SimpleSAML\Module;
+use SimpleSAML\Session;
 
 /**
  * Auth-related utility methods.
@@ -47,7 +50,7 @@ class Auth
             throw new \InvalidArgumentException('Invalid input parameters.');
         }
 
-        $as = new \SimpleSAML\Auth\Simple('admin');
+        $as = new Authentication\Simple('admin');
         return $as->getLogoutURL($returnTo = null);
     }
 
@@ -61,7 +64,7 @@ class Auth
      */
     public static function isAdmin()
     {
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         return $session->isValid('admin') || $session->isValid('login-admin');
     }
 
@@ -84,11 +87,11 @@ class Auth
         }
 
         // not authenticated as admin user, start authentication
-        if (\SimpleSAML\Auth\Source::getById('admin') !== null) {
-            $as = new \SimpleSAML\Auth\Simple('admin');
+        if (Authentication\Source::getById('admin') !== null) {
+            $as = new Authentication\Simple('admin');
             $as->login();
         } else {
-            throw new \SimpleSAML\Error\Exception(
+            throw new Error\Exception(
                 'Cannot find "admin" auth source, and admin privileges are required.'
             );
         }
diff --git a/lib/SimpleSAML/Utils/Config.php b/lib/SimpleSAML/Utils/Config.php
index 663073e00f48582bdeb74cc5ab814cfaf0f8a3e0..ca25cc12462ac07d3b924cc4b200289e04520ae7 100644
--- a/lib/SimpleSAML/Utils/Config.php
+++ b/lib/SimpleSAML/Utils/Config.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Utils;
 
+use SimpleSAML\Configuration;
+
 /**
  * Utility class for SimpleSAMLphp configuration management and manipulation.
  *
@@ -25,7 +27,7 @@ class Config
             throw new \InvalidArgumentException('Invalid input parameters.');
         }
 
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
         $base = $globalConfig->getPathValue('certdir', 'cert/');
         return System::resolvePath($path, $base);
     }
@@ -48,7 +50,7 @@ class Config
      */
     public static function getSecretSalt()
     {
-        $secretSalt = \SimpleSAML\Configuration::getInstance()->getString('secretsalt');
+        $secretSalt = Configuration::getInstance()->getString('secretsalt');
         if ($secretSalt === 'defaultsecretsalt') {
             throw new \InvalidArgumentException('The "secretsalt" configuration option must be set to a secret value.');
         }
diff --git a/lib/SimpleSAML/Utils/Config/Metadata.php b/lib/SimpleSAML/Utils/Config/Metadata.php
index f20a06c2f35a1f43e41aa9e00048077fdcab65d5..c179f18ce44fee21361fb431a7dced063886e01d 100644
--- a/lib/SimpleSAML/Utils/Config/Metadata.php
+++ b/lib/SimpleSAML/Utils/Config/Metadata.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Utils\Config;
 
+use SAML2\Constants;
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+
 /**
  * Class with utilities to fetch different configuration objects from metadata configuration arrays.
  *
@@ -278,9 +282,9 @@ class Metadata
      */
     public static function isHiddenFromDiscovery(array $metadata)
     {
-        \SimpleSAML\Logger::maskErrors(E_ALL);
+        Logger::maskErrors(E_ALL);
         $hidden = in_array(self::$HIDE_FROM_DISCOVERY, $metadata['EntityAttributes'][self::$ENTITY_CATEGORY], true);
-        \SimpleSAML\Logger::popErrorMask();
+        Logger::popErrorMask();
         return $hidden === true;
     }
 
@@ -301,9 +305,9 @@ class Metadata
             $policy = ['Format' => $nameIdPolicy];
         } elseif (is_array($nameIdPolicy)) {
             // handle current configurations specifying an array in the NameIDPolicy config option
-            $nameIdPolicy_cf = \SimpleSAML\Configuration::loadFromArray($nameIdPolicy);
+            $nameIdPolicy_cf = Configuration::loadFromArray($nameIdPolicy);
             $policy = [
-                'Format'      => $nameIdPolicy_cf->getString('Format', \SAML2\Constants::NAMEID_TRANSIENT),
+                'Format'      => $nameIdPolicy_cf->getString('Format', Constants::NAMEID_TRANSIENT),
                 'AllowCreate' => $nameIdPolicy_cf->getBoolean('AllowCreate', true),
             ];
             $spNameQualifier = $nameIdPolicy_cf->getString('SPNameQualifier', false);
@@ -312,7 +316,7 @@ class Metadata
             }
         } elseif ($nameIdPolicy === null) {
             // when NameIDPolicy is unset or set to null, default to transient as before
-            $policy = ['Format' => \SAML2\Constants::NAMEID_TRANSIENT];
+            $policy = ['Format' => Constants::NAMEID_TRANSIENT];
         }
 
         return $policy;
diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php
index 2dc9e7ad2411f7191721c84323ffbc3eb7614b61..fa9b60028595db2cb9189d46b849aa64a200108a 100644
--- a/lib/SimpleSAML/Utils/HTTP.php
+++ b/lib/SimpleSAML/Utils/HTTP.php
@@ -3,10 +3,11 @@
 namespace SimpleSAML\Utils;
 
 use SimpleSAML\Configuration;
+use SimpleSAML\Error;
 use SimpleSAML\Logger;
 use SimpleSAML\Module;
 use SimpleSAML\Session;
-use SimpleSAML\Error;
+use SimpleSAML\XHTML\Template;
 
 /**
  * HTTP-related utility methods.
@@ -735,6 +736,7 @@ class HTTP
         return substr($url, $start, $length);
     }
 
+
     /**
      * Retrieve our own host together with the URL path. Please note this function will return the base URL for the
      * current SP, as defined in the global configuration.
@@ -1225,7 +1227,7 @@ class HTTP
             self::redirect(self::getSecurePOSTRedirectURL($destination, $data));
         }
 
-        $p = new \SimpleSAML\XHTML\Template($config, 'post.php');
+        $p = new Template($config, 'post.php');
         $p->data['destination'] = $destination;
         $p->data['post'] = $data;
         $p->show();
diff --git a/lib/SimpleSAML/Utils/System.php b/lib/SimpleSAML/Utils/System.php
index e0e93fab83055f2bd6f0198b96a5cd1f36e691be..6607edd6e9dd11470312fcf9bcbeb6fa5b1b9d4a 100644
--- a/lib/SimpleSAML/Utils/System.php
+++ b/lib/SimpleSAML/Utils/System.php
@@ -2,6 +2,7 @@
 
 namespace SimpleSAML\Utils;
 
+use SimpleSAML\Configuration;
 use SimpleSAML\Error;
 
 /**
@@ -72,7 +73,7 @@ class System
      */
     public static function getTempDir()
     {
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
 
         $tempDir = rtrim(
             $globalConfig->getString(
@@ -123,7 +124,7 @@ class System
     public static function resolvePath($path, $base = null)
     {
         if ($base === null) {
-            $config = \SimpleSAML\Configuration::getInstance();
+            $config = Configuration::getInstance();
             $base = $config->getBaseDir();
         }
 
diff --git a/lib/SimpleSAML/Utils/Time.php b/lib/SimpleSAML/Utils/Time.php
index 78246f9415fdd9d886b8c75c7d7c072b01821a9e..9f0c690f8d5b1eb413b9a627401b892c9e411a2e 100644
--- a/lib/SimpleSAML/Utils/Time.php
+++ b/lib/SimpleSAML/Utils/Time.php
@@ -8,6 +8,8 @@
 
 namespace SimpleSAML\Utils;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
 use SimpleSAML\Logger;
 
 class Time
@@ -54,12 +56,12 @@ class Time
             return;
         }
 
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
 
         $timezone = $globalConfig->getString('timezone', null);
         if ($timezone !== null) {
             if (!date_default_timezone_set($timezone)) {
-                throw new \SimpleSAML\Error\Exception('Invalid timezone set in the "timezone" option in config.php.');
+                throw new Error\Exception('Invalid timezone set in the "timezone" option in config.php.');
             }
             self::$tz_initialized = true;
             return;
diff --git a/lib/SimpleSAML/Utils/XML.php b/lib/SimpleSAML/Utils/XML.php
index da5e66e3c798778a78e4511a89388ccc46835f8d..c517b0db8e440b98965c023fe9245a50e5474427 100644
--- a/lib/SimpleSAML/Utils/XML.php
+++ b/lib/SimpleSAML/Utils/XML.php
@@ -8,6 +8,14 @@
 
 namespace SimpleSAML\Utils;
 
+use DOMComment;
+use DOMDocument;
+use DOMElement;
+use DOMNode;
+use DOMText;
+use SAML2\DOMDocumentFactory;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
 use SimpleSAML\Logger;
 use SimpleSAML\XML\Errors;
 
@@ -41,12 +49,12 @@ class XML
 
         // a SAML message should not contain a doctype-declaration
         if (strpos($message, '<!DOCTYPE') !== false) {
-            throw new \SimpleSAML\Error\Exception('XML contained a doctype declaration.');
+            throw new Error\Exception('XML contained a doctype declaration.');
         }
 
         // see if debugging is enabled for XML validation
-        $debug = \SimpleSAML\Configuration::getInstance()->getArrayize('debug', ['validatexml' => false]);
-        $enabled = \SimpleSAML\Configuration::getInstance()->getBoolean('debug.validatexml', false);
+        $debug = Configuration::getInstance()->getArrayize('debug', ['validatexml' => false]);
+        $enabled = Configuration::getInstance()->getBoolean('debug.validatexml', false);
 
         if (!(in_array('validatexml', $debug, true) // implicitly enabled
             || (array_key_exists('validatexml', $debug) && $debug['validatexml'] === true)
@@ -94,12 +102,12 @@ class XML
      */
     public static function debugSAMLMessage($message, $type)
     {
-        if (!(is_string($type) && (is_string($message) || $message instanceof \DOMElement))) {
+        if (!(is_string($type) && (is_string($message) || $message instanceof DOMElement))) {
             throw new \InvalidArgumentException('Invalid input parameters.');
         }
 
         // see if debugging is enabled for SAML messages
-        $debug = \SimpleSAML\Configuration::getInstance()->getArrayize('debug', ['saml' => false]);
+        $debug = Configuration::getInstance()->getArrayize('debug', ['saml' => false]);
 
         if (!(in_array('saml', $debug, true) // implicitly enabled
             || (array_key_exists('saml', $debug) && $debug['saml'] === true)
@@ -111,7 +119,7 @@ class XML
             return;
         }
 
-        if ($message instanceof \DOMElement) {
+        if ($message instanceof DOMElement) {
             $message = $message->ownerDocument->saveXML($message);
         }
 
@@ -155,7 +163,7 @@ class XML
      *
      * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
      */
-    public static function formatDOMElement(\DOMNode $root, $indentBase = '')
+    public static function formatDOMElement(DOMNode $root, $indentBase = '')
     {
         if (!is_string($indentBase)) {
             throw new \InvalidArgumentException('Invalid input parameters');
@@ -169,10 +177,10 @@ class XML
             /** @var \DOMNode $child */
             $child = $root->childNodes->item($i);
 
-            if ($child instanceof \DOMText) {
+            if ($child instanceof DOMText) {
                 $textNodes[] = $child;
                 $fullText .= $child->wholeText;
-            } elseif ($child instanceof \DOMComment || $child instanceof \DOMElement) {
+            } elseif ($child instanceof DOMComment || $child instanceof DOMElement) {
                 $childNodes[] = $child;
             } else {
                 // unknown node type. We don't know how to format this
@@ -202,7 +210,7 @@ class XML
 
         if ($hasText) {
             // only text - add a single text node to the element with the full text
-            $root->appendChild(new \DOMText($fullText));
+            $root->appendChild(new DOMText($fullText));
             return;
         }
 
@@ -217,7 +225,7 @@ class XML
         $childIndentation = $indentBase.'  ';
         foreach ($childNodes as $node) {
             // add indentation before node
-            $root->insertBefore(new \DOMText("\n".$childIndentation), $node);
+            $root->insertBefore(new DOMText("\n".$childIndentation), $node);
 
             // format child elements
             if ($node instanceof \DOMElement) {
@@ -226,7 +234,7 @@ class XML
         }
 
         // add indentation before closing tag
-        $root->appendChild(new \DOMText("\n".$indentBase));
+        $root->appendChild(new DOMText("\n".$indentBase));
     }
 
 
@@ -252,7 +260,7 @@ class XML
         }
 
         try {
-            $doc = \SAML2\DOMDocumentFactory::fromString($xml);
+            $doc = DOMDocumentFactory::fromString($xml);
         } catch (\Exception $e) {
             throw new \DOMException('Error parsing XML string.');
         }
@@ -279,7 +287,7 @@ class XML
      * @throws \InvalidArgumentException If $element is not an instance of DOMElement, $localName is not a string or
      *     $namespaceURI is not a string.
      */
-    public static function getDOMChildren(\DOMNode $element, $localName, $namespaceURI)
+    public static function getDOMChildren(DOMNode $element, $localName, $namespaceURI)
     {
         if (!is_string($localName) || !is_string($namespaceURI)) {
             throw new \InvalidArgumentException('Invalid input parameters.');
@@ -292,7 +300,7 @@ class XML
             $child = $element->childNodes->item($i);
 
             // skip text nodes and comment elements
-            if ($child instanceof \DOMText || $child instanceof \DOMComment) {
+            if ($child instanceof DOMText || $child instanceof DOMComment) {
                 continue;
             }
 
@@ -315,15 +323,15 @@ class XML
      *
      * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
      */
-    public static function getDOMText(\DOMElement $element)
+    public static function getDOMText(DOMElement $element)
     {
         $txt = '';
 
         for ($i = 0; $i < $element->childNodes->length; $i++) {
             /** @var \DOMElement $child */
             $child = $element->childNodes->item($i);
-            if (!($child instanceof \DOMText)) {
-                throw new \SimpleSAML\Error\Exception($element->localName.' contained a non-text child node.');
+            if (!($child instanceof DOMText)) {
+                throw new Error\Exception($element->localName.' contained a non-text child node.');
             }
 
             $txt .= $child->wholeText;
@@ -356,7 +364,7 @@ class XML
      * @author Andreas Solberg, UNINETT AS <andreas.solberg@uninett.no>
      * @author Olav Morken, UNINETT AS <olav.morken@uninett.no>
      */
-    public static function isDOMNodeOfType(\DOMNode $element, $name, $nsURI)
+    public static function isDOMNodeOfType(DOMNode $element, $name, $nsURI)
     {
         if (!is_string($name) || !is_string($nsURI) || strlen($nsURI) === 0) {
             // most likely a comment-node
@@ -412,18 +420,18 @@ class XML
      */
     public static function isValid($xml, $schema)
     {
-        if (!(is_string($schema) && (is_string($xml) || $xml instanceof \DOMDocument))) {
+        if (!(is_string($schema) && (is_string($xml) || $xml instanceof DOMDocument))) {
             throw new \InvalidArgumentException('Invalid input parameters.');
         }
 
         Errors::begin();
 
-        if ($xml instanceof \DOMDocument) {
+        if ($xml instanceof DOMDocument) {
             $dom = $xml;
             $res = true;
         } else {
             try {
-                $dom = \SAML2\DOMDocumentFactory::fromString($xml);
+                $dom = DOMDocumentFactory::fromString($xml);
                 $res = true;
             } catch (\Exception $e) {
                 $res = false;
@@ -431,7 +439,7 @@ class XML
         }
 
         if ($res) {
-            $config = \SimpleSAML\Configuration::getInstance();
+            $config = Configuration::getInstance();
             /** @var string $schemaPath */
             $schemaPath = $config->resolvePath('schemas');
             $schemaFile = $schemaPath.'/'.$schema;
diff --git a/lib/SimpleSAML/XHTML/IdPDisco.php b/lib/SimpleSAML/XHTML/IdPDisco.php
index 0fb503807b7271a313d5fcdd26043d035d7d8474..39d5f9c22a0fa67ed79152ae308ce933804c8e9a 100644
--- a/lib/SimpleSAML/XHTML/IdPDisco.php
+++ b/lib/SimpleSAML/XHTML/IdPDisco.php
@@ -2,6 +2,12 @@
 
 namespace SimpleSAML\XHTML;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Metadata\MetaDataStorageHandler;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+
 /**
  * This class implements a generic IdP discovery service, for use in various IdP
  * discovery service pages. This should reduce code duplication.
@@ -31,7 +37,6 @@ class IdPDisco
      */
     protected $instance;
 
-
     /**
      * An instance of the metadata handler, which will allow us to fetch metadata about IdPs.
      *
@@ -39,7 +44,6 @@ class IdPDisco
      */
     protected $metadata;
 
-
     /**
      * The users session.
      *
@@ -47,7 +51,6 @@ class IdPDisco
      */
     protected $session;
 
-
     /**
      * The metadata sets we find allowed entities in, in prioritized order.
      *
@@ -55,7 +58,6 @@ class IdPDisco
      */
     protected $metadataSets;
 
-
     /**
      * The entity id of the SP which accesses this IdP discovery service.
      *
@@ -78,7 +80,6 @@ class IdPDisco
      */
     protected $setIdPentityID = null;
 
-
     /**
      * The name of the query parameter which should contain the users choice of IdP.
      * This option default to 'entityID' for Shibboleth compatibility.
@@ -119,9 +120,9 @@ class IdPDisco
         assert(is_string($instance));
 
         // initialize standard classes
-        $this->config = \SimpleSAML\Configuration::getInstance();
-        $this->metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
-        $this->session = \SimpleSAML\Session::getSessionFromRequest();
+        $this->config = Configuration::getInstance();
+        $this->metadata = MetaDataStorageHandler::getMetadataHandler();
+        $this->session = Session::getSessionFromRequest();
         $this->instance = $instance;
         $this->metadataSets = $metadataSets;
 
@@ -145,7 +146,7 @@ class IdPDisco
         if (!array_key_exists('return', $_GET)) {
             throw new \Exception('Missing parameter: return');
         } else {
-            $this->returnURL = \SimpleSAML\Utils\HTTP::checkURLAllowed($_GET['return']);
+            $this->returnURL = Utils\HTTP::checkURLAllowed($_GET['return']);
         }
 
         $this->isPassive = false;
@@ -177,7 +178,7 @@ class IdPDisco
      */
     protected function log($message)
     {
-        \SimpleSAML\Logger::info('idpDisco.'.$this->instance.': '.$message);
+        Logger::info('idpDisco.'.$this->instance.': '.$message);
     }
 
 
@@ -224,7 +225,7 @@ class IdPDisco
             'httponly' => false,
         ];
 
-        \SimpleSAML\Utils\HTTP::setCookie($prefixedName, $value, $params, false);
+        Utils\HTTP::setCookie($prefixedName, $value, $params, false);
     }
 
 
@@ -520,7 +521,7 @@ class IdPDisco
             $extDiscoveryStorage = $this->config->getString('idpdisco.extDiscoveryStorage', null);
             if ($extDiscoveryStorage !== null) {
                 $this->log('Choice made ['.$idp.'] (Forwarding to external discovery storage)');
-                \SimpleSAML\Utils\HTTP::redirectTrustedURL($extDiscoveryStorage, [
+                Utils\HTTP::redirectTrustedURL($extDiscoveryStorage, [
                     'entityID'      => $this->spEntityId,
                     'IdPentityID'   => $idp,
                     'returnIDParam' => $this->returnIdParam,
@@ -531,13 +532,13 @@ class IdPDisco
                 $this->log(
                     'Choice made ['.$idp.'] (Redirecting the user back. returnIDParam='.$this->returnIdParam.')'
                 );
-                \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL, [$this->returnIdParam => $idp]);
+                Utils\HTTP::redirectTrustedURL($this->returnURL, [$this->returnIdParam => $idp]);
             }
         }
 
         if ($this->isPassive) {
             $this->log('Choice not made. (Redirecting the user back without answer)');
-            \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL);
+            Utils\HTTP::redirectTrustedURL($this->returnURL);
         }
     }
 
@@ -569,7 +570,7 @@ class IdPDisco
                 'Choice made ['.$idpintersection[0].'] (Redirecting the user back. returnIDParam='.
                 $this->returnIdParam.')'
             );
-            \SimpleSAML\Utils\HTTP::redirectTrustedURL(
+            Utils\HTTP::redirectTrustedURL(
                 $this->returnURL,
                 [$this->returnIdParam => $idpintersection[0]]
             );
@@ -618,7 +619,7 @@ class IdPDisco
             }
             if (!empty($data['icon'])) {
                 $newlist[$entityid]['icon'] = $data['icon'];
-                $newlist[$entityid]['iconurl'] = \SimpleSAML\Utils\HTTP::resolveURL($data['icon']);
+                $newlist[$entityid]['iconurl'] = Utils\HTTP::resolveURL($data['icon']);
             }
         }
         usort(
@@ -638,7 +639,7 @@ class IdPDisco
         $t->data['return'] = $this->returnURL;
         $t->data['returnIDParam'] = $this->returnIdParam;
         $t->data['entityID'] = $this->spEntityId;
-        $t->data['urlpattern'] = htmlspecialchars(\SimpleSAML\Utils\HTTP::getSelfURLNoQuery());
+        $t->data['urlpattern'] = htmlspecialchars(Utils\HTTP::getSelfURLNoQuery());
         $t->data['rememberenabled'] = $this->config->getBoolean('idpdisco.enableremember', false);
         $t->show();
     }
diff --git a/lib/SimpleSAML/XHTML/Template.php b/lib/SimpleSAML/XHTML/Template.php
index f55f68e0db338f68b957f217889c2b3d848dc190..b1c3cca00719a91f8a44a91c6c7ad9a076baf178 100644
--- a/lib/SimpleSAML/XHTML/Template.php
+++ b/lib/SimpleSAML/XHTML/Template.php
@@ -11,15 +11,19 @@ namespace SimpleSAML\XHTML;
 
 use JaimePerez\TwigConfigurableI18n\Twig\Environment as Twig_Environment;
 use JaimePerez\TwigConfigurableI18n\Twig\Extensions\Extension\I18n as Twig_Extensions_Extension_I18n;
-use Symfony\Component\HttpFoundation\Response;
 
 use SimpleSAML\Configuration;
-use SimpleSAML\Utils\HTTP;
 use SimpleSAML\Locale\Language;
 use SimpleSAML\Locale\Localization;
 use SimpleSAML\Locale\Translate;
 use SimpleSAML\Logger;
 use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
+use Symfony\Component\HttpFoundation\Response;
+use Twig\Loader\FilesystemLoader;
+use Twig\TwigFilter;
+use Twig\TwigFunction;
 
 class Template extends Response
 {
@@ -246,7 +250,7 @@ class Template extends Response
 
         // default, themeless templates are checked last
         $templateDirs[] = [
-            \Twig\Loader\FilesystemLoader::MAIN_NAMESPACE => $this->configuration->resolvePath('templates')
+            FilesystemLoader::MAIN_NAMESPACE => $this->configuration->resolvePath('templates')
         ];
         foreach ($templateDirs as $entry) {
             $loader->addPath($entry[key($entry)], key($entry));
@@ -309,7 +313,7 @@ class Template extends Response
 
         // add a filter for translations out of arrays
         $twig->addFilter(
-            new \Twig\TwigFilter(
+            new TwigFilter(
                 'translateFromArray',
                 [Translate::class, 'translateFromArray'],
                 ['needs_context' => true]
@@ -317,7 +321,7 @@ class Template extends Response
         );
 
         // add an asset() function
-        $twig->addFunction(new \Twig\TwigFunction('asset', [$this, 'asset']));
+        $twig->addFunction(new TwigFunction('asset', [$this, 'asset']));
 
         if ($this->controller !== null) {
             $this->controller->setUpTwig($twig);
@@ -356,7 +360,7 @@ class Template extends Response
             }
 
             // set correct name for the default namespace
-            $ns = ($entry === 'default') ? \Twig\Loader\FilesystemLoader::MAIN_NAMESPACE : $entry;
+            $ns = ($entry === 'default') ? FilesystemLoader::MAIN_NAMESPACE : $entry;
             $themeTemplateDirs[] = [$ns => $themeDir.'/'.$entry];
         }
         return $themeTemplateDirs;
@@ -423,7 +427,7 @@ class Template extends Response
                 $langname = $this->translator->getLanguage()->getLanguageLocalizedName($lang);
                 $url = false;
                 if (!$current) {
-                    $url = htmlspecialchars(HTTP::addURLParameters(
+                    $url = htmlspecialchars(Utils\HTTP::addURLParameters(
                         '',
                         [$parameterName => $lang]
                     ));
diff --git a/lib/SimpleSAML/XHTML/TemplateControllerInterface.php b/lib/SimpleSAML/XHTML/TemplateControllerInterface.php
index 082320b234efebfb07d617d96e475c429d1d37e2..bead9a1c69c6209b27b5805115c9d57e2c6a56ae 100644
--- a/lib/SimpleSAML/XHTML/TemplateControllerInterface.php
+++ b/lib/SimpleSAML/XHTML/TemplateControllerInterface.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\XHTML;
 
+use Twig\Environment;
+
 /**
  * Interface that allows modules to run several hooks for templates.
  *
@@ -17,7 +19,7 @@ interface TemplateControllerInterface
      *
      * @return void
      */
-    public function setUpTwig(\Twig\Environment &$twig);
+    public function setUpTwig(Environment &$twig);
 
 
     /**
diff --git a/lib/SimpleSAML/XHTML/TemplateLoader.php b/lib/SimpleSAML/XHTML/TemplateLoader.php
index b8de4368e5457709a1604050fc6f1432214c17de..a2c6571478d5c8d488a81e9b763d70c6b0a14e16 100644
--- a/lib/SimpleSAML/XHTML/TemplateLoader.php
+++ b/lib/SimpleSAML/XHTML/TemplateLoader.php
@@ -1,8 +1,9 @@
 <?php
 
-
 namespace SimpleSAML\XHTML;
 
+use SimpleSAML\Module;
+
 /**
  * This class extends the Twig\Loader\FilesystemLoader so that we can load templates from modules in twig, even
  * when the main template is not part of a module (or the same one).
@@ -60,10 +61,10 @@ class TemplateLoader extends \Twig\Loader\FilesystemLoader
      */
     public static function getModuleTemplateDir($module)
     {
-        if (!\SimpleSAML\Module::isModuleEnabled($module)) {
+        if (!Module::isModuleEnabled($module)) {
             throw new \InvalidArgumentException('The module \''.$module.'\' is not enabled.');
         }
-        $moduledir = \SimpleSAML\Module::getModuleDir($module);
+        $moduledir = Module::getModuleDir($module);
         // check if module has a /templates dir, if so, append
         $templatedir = $moduledir.'/templates';
         if (!is_dir($templatedir)) {
diff --git a/lib/SimpleSAML/XML/Errors.php b/lib/SimpleSAML/XML/Errors.php
index 01720fb8101b120797a58e1adbf875213d937bba..9871571904d8ed8aacbce0283baf93d091d1085a 100644
--- a/lib/SimpleSAML/XML/Errors.php
+++ b/lib/SimpleSAML/XML/Errors.php
@@ -81,7 +81,6 @@ class Errors
      */
     public static function end()
     {
-
         // Check whether the error access functions are present
         if (!function_exists('libxml_use_internal_errors')) {
             // Pretend that no errors occurred
diff --git a/lib/SimpleSAML/XML/Shib13/AuthnRequest.php b/lib/SimpleSAML/XML/Shib13/AuthnRequest.php
index 80bd641c21f03ef8f521f63c2242cbde6bc18015..41e8e2964bf9e142dc90869f4b8e08c5054b022d 100644
--- a/lib/SimpleSAML/XML/Shib13/AuthnRequest.php
+++ b/lib/SimpleSAML/XML/Shib13/AuthnRequest.php
@@ -10,6 +10,8 @@
 
 namespace SimpleSAML\XML\Shib13;
 
+use SimpleSAML\Metadata\MetaDataStorageHandler;
+
 class AuthnRequest
 {
     /** @var string|null */
@@ -64,7 +66,7 @@ class AuthnRequest
      */
     public function createRedirect($destination, $shire)
     {
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $idpmetadata = $metadata->getMetaDataConfig($destination, 'shib13-idp-remote');
 
         $desturl = $idpmetadata->getDefaultEndpoint(
diff --git a/lib/SimpleSAML/XML/Shib13/AuthnResponse.php b/lib/SimpleSAML/XML/Shib13/AuthnResponse.php
index 0a0bf47e1d2a7287712811da590ce8055f6712a3..d04983b3114fe1f4a6303d330fe096e87b1c8e4a 100644
--- a/lib/SimpleSAML/XML/Shib13/AuthnResponse.php
+++ b/lib/SimpleSAML/XML/Shib13/AuthnResponse.php
@@ -11,11 +11,12 @@ namespace SimpleSAML\XML\Shib13;
 
 use DOMDocument;
 use DOMNode;
+use DOMXpath;
 use SAML2\DOMDocumentFactory;
-use SAML2\Utils;
-use SimpleSAML\Utils\Config;
-use SimpleSAML\Utils\Random;
-use SimpleSAML\Utils\Time;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Metadata\MetaDataStorageHandler;
+use SimpleSAML\Utils;
 use SimpleSAML\XML\Validator;
 
 class AuthnResponse
@@ -121,7 +122,7 @@ class AuthnResponse
         $issuer = $this->getIssuer();
 
         // Get the metadata of the issuer
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $md = $metadata->getMetaDataConfig($issuer, 'shib13-idp-remote');
 
         $publicKeys = $md->getPublicKeys('signing');
@@ -141,9 +142,9 @@ class AuthnResponse
             $this->validator->validateFingerprint($certFingerprints);
         } elseif ($md->hasValue('caFile')) {
             // Validate against CA
-            $this->validator->validateCA(Config::getCertPath($md->getString('caFile')));
+            $this->validator->validateCA(Utils\Config::getCertPath($md->getString('caFile')));
         } else {
-            throw new \SimpleSAML\Error\Exception(
+            throw new Error\Exception(
                 'Missing certificate in Shibboleth 1.3 IdP Remote metadata for identity provider ['.$issuer.'].'
             );
         }
@@ -174,7 +175,7 @@ class AuthnResponse
             $node = dom_import_simplexml($node);
         }
 
-        assert($node instanceof \DOMNode);
+        assert($node instanceof DOMNode);
 
         return $this->validator->isNodeValidated($node);
     }
@@ -191,15 +192,15 @@ class AuthnResponse
     private function doXPathQuery($query, $node = null)
     {
         assert(is_string($query));
-        assert($this->dom instanceof \DOMDocument);
+        assert($this->dom instanceof DOMDocument);
 
         if ($node === null) {
             $node = $this->dom->documentElement;
         }
 
-        assert($node instanceof \DOMNode);
+        assert($node instanceof DOMNode);
 
-        $xPath = new \DOMXpath($this->dom);
+        $xPath = new DOMXpath($this->dom);
         $xPath->registerNamespace('shibp', self::SHIB_PROTOCOL_NS);
         $xPath->registerNamespace('shib', self::SHIB_ASSERT_NS);
 
@@ -232,11 +233,11 @@ class AuthnResponse
      */
     public function getAttributes()
     {
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $md = $metadata->getMetaData($this->getIssuer(), 'shib13-idp-remote');
         $base64 = isset($md['base64attributes']) ? $md['base64attributes'] : false;
 
-        if (!($this->dom instanceof \DOMDocument)) {
+        if (!($this->dom instanceof DOMDocument)) {
             return [];
         }
 
@@ -347,7 +348,7 @@ class AuthnResponse
      * @param array|null $attributes The attributes which should be included in the response.
      * @return string The response.
      */
-    public function generate(\SimpleSAML\Configuration $idp, \SimpleSAML\Configuration $sp, $shire, $attributes)
+    public function generate(Configuration $idp, Configuration $sp, $shire, $attributes)
     {
         assert(is_string($shire));
         assert($attributes === null || is_array($attributes));
@@ -360,16 +361,16 @@ class AuthnResponse
             $scopedAttributes = [];
         }
 
-        $id = Random::generateID();
+        $id = Utils\Random::generateID();
         
-        $issueInstant = Time::generateTimestamp();
+        $issueInstant = Utils\Time::generateTimestamp();
         
         // 30 seconds timeskew back in time to allow differing clocks
-        $notBefore = Time::generateTimestamp(time() - 30);
+        $notBefore = Utils\Time::generateTimestamp(time() - 30);
         
         
-        $assertionExpire = Time::generateTimestamp(time() + 300); // 5 minutes
-        $assertionid = Random::generateID();
+        $assertionExpire = Utils\Time::generateTimestamp(time() + 300); // 5 minutes
+        $assertionid = Utils\Random::generateID();
 
         $spEntityId = $sp->getString('entityid');
 
@@ -377,7 +378,7 @@ class AuthnResponse
         $base64 = $sp->getBoolean('base64attributes', false);
 
         $namequalifier = $sp->getString('NameQualifier', $spEntityId);
-        $nameid = Random::generateID();
+        $nameid = Utils\Random::generateID();
         $subjectNode =
             '<Subject>'.
             '<NameIdentifier'.
@@ -505,14 +506,14 @@ class AuthnResponse
         $currentTime = time();
 
         if (!empty($start)) {
-            $startTime = Utils::xsDateTimeToTimestamp($start);
+            $startTime = \SAML2\Utils::xsDateTimeToTimestamp($start);
             // allow for a 10 minute difference in time
             if (($startTime < 0) || (($startTime - 600) > $currentTime)) {
                 return false;
             }
         }
         if (!empty($end)) {
-            $endTime = Utils::xsDateTimeToTimestamp($end);
+            $endTime = \SAML2\Utils::xsDateTimeToTimestamp($end);
             if (($endTime < 0) || ($endTime <= $currentTime)) {
                 return false;
             }
diff --git a/lib/SimpleSAML/XML/Signer.php b/lib/SimpleSAML/XML/Signer.php
index ee58c4c092c4aa3b512905ab62bfc6c39c19b392..235335b649628b2523c96ceccca9d02165987454 100644
--- a/lib/SimpleSAML/XML/Signer.php
+++ b/lib/SimpleSAML/XML/Signer.php
@@ -16,7 +16,7 @@ use DOMElement;
 use DOMText;
 use RobRichards\XMLSecLibs\XMLSecurityDSig;
 use RobRichards\XMLSecLibs\XMLSecurityKey;
-use SimpleSAML\Utils\Config;
+use SimpleSAML\Utils;
 
 class Signer
 {
@@ -132,7 +132,7 @@ class Signer
         assert(is_bool($full_path));
 
         if (!$full_path) {
-            $keyFile = Config::getCertPath($file);
+            $keyFile = Utils\Config::getCertPath($file);
         } else {
             $keyFile = $file;
         }
@@ -196,7 +196,7 @@ class Signer
         assert(is_bool($full_path));
 
         if (!$full_path) {
-            $certFile = Config::getCertPath($file);
+            $certFile = Utils\Config::getCertPath($file);
         } else {
             $certFile = $file;
         }
@@ -245,7 +245,7 @@ class Signer
         assert(is_bool($full_path));
 
         if (!$full_path) {
-            $certFile = Config::getCertPath($file);
+            $certFile = Utils\Config::getCertPath($file);
         } else {
             $certFile = $file;
         }
diff --git a/modules/admin/lib/ConfigController.php b/modules/admin/lib/ConfigController.php
index a7844be3cac84d4bb2e40fbb22fe301409b4d939..97786c4ba0bf168af1dfea3a1d3783670de180a7 100644
--- a/modules/admin/lib/ConfigController.php
+++ b/modules/admin/lib/ConfigController.php
@@ -2,9 +2,13 @@
 
 namespace SimpleSAML\Module\admin;
 
+use SimpleSAML\Configuration;
 use SimpleSAML\HTTP\RunnableResponse;
 use SimpleSAML\Locale\Translate;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Module;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+use SimpleSAML\XHTML\Template;
 use Symfony\Component\HttpFoundation\Request;
 
 /**
@@ -35,7 +39,7 @@ class ConfigController
      * @param \SimpleSAML\Configuration $config The configuration to use.
      * @param \SimpleSAML\Session $session The current user session.
      */
-    public function __construct(\SimpleSAML\Configuration $config, \SimpleSAML\Session $session)
+    public function __construct(Configuration $config, Session $session)
     {
         $this->config = $config;
         $this->session = $session;
@@ -52,28 +56,28 @@ class ConfigController
      */
     public function diagnostics(Request $request)
     {
-        \SimpleSAML\Utils\Auth::requireAdmin();
+        Utils\Auth::requireAdmin();
 
-        $t = new \SimpleSAML\XHTML\Template($this->config, 'admin:diagnostics.twig');
+        $t = new Template($this->config, 'admin:diagnostics.twig');
         $t->data = [
             'remaining' => $this->session->getAuthData('admin', 'Expire') - time(),
-            'logouturl' => \SimpleSAML\Utils\Auth::getAdminLogoutURL(),
+            'logouturl' => Utils\Auth::getAdminLogoutURL(),
             'items' => [
                 'HTTP_HOST' => [$request->getHost()],
                 'HTTPS' => $request->isSecure() ? ['on'] : [],
                 'SERVER_PROTOCOL' => [$request->getProtocolVersion()],
-                'getBaseURL()' => [HTTP::getBaseURL()],
-                'getSelfHost()' => [HTTP::getSelfHost()],
-                'getSelfHostWithNonStandardPort()' => [HTTP::getSelfHostWithNonStandardPort()],
-                'getSelfURLHost()' => [HTTP::getSelfURLHost()],
-                'getSelfURLNoQuery()' => [HTTP::getSelfURLNoQuery()],
-                'getSelfHostWithPath()' => [HTTP::getSelfHostWithPath()],
-                'getFirstPathElement()' => [HTTP::getFirstPathElement()],
-                'getSelfURL()' => [HTTP::getSelfURL()],
+                'getBaseURL()' => [Utils\HTTP::getBaseURL()],
+                'getSelfHost()' => [Utils\HTTP::getSelfHost()],
+                'getSelfHostWithNonStandardPort()' => [Utils\HTTP::getSelfHostWithNonStandardPort()],
+                'getSelfURLHost()' => [Utils\HTTP::getSelfURLHost()],
+                'getSelfURLNoQuery()' => [Utils\HTTP::getSelfURLNoQuery()],
+                'getSelfHostWithPath()' => [Utils\HTTP::getSelfHostWithPath()],
+                'getFirstPathElement()' => [Utils\HTTP::getFirstPathElement()],
+                'getSelfURL()' => [Utils\HTTP::getSelfURL()],
             ],
         ];
 
-        $this->menu->addOption('logout', \SimpleSAML\Utils\Auth::getAdminLogoutURL(), Translate::noop('Log out'));
+        $this->menu->addOption('logout', $t->data['logouturl'], Translate::noop('Log out'));
         return $this->menu->insert($t);
     }
 
@@ -85,20 +89,20 @@ class ConfigController
      */
     public function main()
     {
-        \SimpleSAML\Utils\Auth::requireAdmin();
+        Utils\Auth::requireAdmin();
 
-        $t = new \SimpleSAML\XHTML\Template($this->config, 'admin:config.twig');
+        $t = new Template($this->config, 'admin:config.twig');
         $t->data = [
             'warnings' => $this->getWarnings(),
             'directory' => $this->config->getBaseDir(),
             'version' => $this->config->getVersion(),
             'links' => [
                 [
-                    'href' => \SimpleSAML\Module::getModuleURL('admin/diagnostics'),
+                    'href' => Module::getModuleURL('admin/diagnostics'),
                     'text' => Translate::noop('Diagnostics on hostname, port and protocol')
                 ],
                 [
-                    'href' => \SimpleSAML\Module::getModuleURL('admin/phpinfo'),
+                    'href' => Module::getModuleURL('admin/phpinfo'),
                     'text' => Translate::noop('Information on your PHP installation')
                 ]
             ],
@@ -107,11 +111,11 @@ class ConfigController
                 'shib13idp' => $this->config->getBoolean('enable.shib13-idp', false),
             ],
             'funcmatrix' => $this->getPrerequisiteChecks(),
-            'logouturl' => \SimpleSAML\Utils\Auth::getAdminLogoutURL(),
+            'logouturl' => Utils\Auth::getAdminLogoutURL(),
         ];
 
-        \SimpleSAML\Module::callHooks('configpage', $t);
-        $this->menu->addOption('logout', \SimpleSAML\Utils\Auth::getAdminLogoutURL(), Translate::noop('Log out'));
+        Module::callHooks('configpage', $t);
+        $this->menu->addOption('logout', Utils\Auth::getAdminLogoutURL(), Translate::noop('Log out'));
         return $this->menu->insert($t);
     }
 
@@ -239,14 +243,14 @@ class ConfigController
                 ]
             ],
             'ldap_bind' => [
-                'required' => \SimpleSAML\Module::isModuleEnabled('ldap') ? 'required' : 'optional',
+                'required' => Module::isModuleEnabled('ldap') ? 'required' : 'optional',
                 'descr' => [
                     'optional' => Translate::noop('LDAP extension (required if an LDAP backend is used)'),
                     'required' => Translate::noop('LDAP extension'),
                 ]
             ],
             'radius_auth_open' => [
-                'required' => \SimpleSAML\Module::isModuleEnabled('radius') ? 'required' : 'optional',
+                'required' => Module::isModuleEnabled('radius') ? 'required' : 'optional',
                 'descr' => [
                     'optional' => Translate::noop('Radius extension (required if a radius backend is used)'),
                     'required' => Translate::noop('Radius extension'),
@@ -330,7 +334,7 @@ class ConfigController
         $warnings = [];
 
         // make sure we're using HTTPS
-        if (!\SimpleSAML\Utils\HTTP::isHTTPS()) {
+        if (!Utils\HTTP::isHTTPS()) {
             $warnings[] = Translate::noop(
                 '<strong>You are not using HTTPS</strong> to protect communications with your users. HTTP works fine '.
                 'for testing purposes, but in a production environment you should use HTTPS. <a '.
diff --git a/modules/admin/lib/FederationController.php b/modules/admin/lib/FederationController.php
index b0bcc47a4a9b1d824d9113b22fe58d43e786e7d9..1929504c332f9acc1396a70dd151d5f45c9f9797 100644
--- a/modules/admin/lib/FederationController.php
+++ b/modules/admin/lib/FederationController.php
@@ -2,17 +2,21 @@
 
 namespace SimpleSAML\Module\admin;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Configuration;
+use SimpleSAML\HTTP\RunnableResponse;
 use SimpleSAML\Locale\Translate;
+use SimpleSAML\Logger;
 use SimpleSAML\Metadata\MetaDataStorageHandler;
 use SimpleSAML\Metadata\SAMLBuilder;
+use SimpleSAML\Metadata\SAMLParser;
+use SimpleSAML\Metadata\Signer;
 use SimpleSAML\Module;
 use SimpleSAML\Module\adfs\IdP\ADFS as ADFS_IdP;
 use SimpleSAML\Module\saml\IdP\SAML1 as SAML1_IdP;
 use SimpleSAML\Module\saml\IdP\SAML2 as SAML2_IdP;
-use SimpleSAML\Utils\Auth;
-
-use SimpleSAML\HTTP\RunnableResponse;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Utils;
+use SimpleSAML\XHTML\Template;
 use Symfony\Component\HttpFoundation\Request;
 
 /**
@@ -40,7 +44,7 @@ class FederationController
      *
      * @param \SimpleSAML\Configuration $config The configuration to use.
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         $this->config = $config;
         $this->menu = new Menu();
@@ -57,7 +61,7 @@ class FederationController
      */
     public function main()
     {
-        Auth::requireAdmin();
+        Utils\Auth::requireAdmin();
 
         // initialize basic metadata array
         $hostedSPs = $this->getHostedSP();
@@ -77,7 +81,7 @@ class FederationController
         ];
 
         // initialize template and language
-        $t = new \SimpleSAML\XHTML\Template($this->config, 'admin:federation.twig');
+        $t = new Template($this->config, 'admin:federation.twig');
         $language = $t->getTranslator()->getLanguage()->getLanguage();
         $defaultLang = $this->config->getString('language.default', 'en');
 
@@ -140,7 +144,7 @@ class FederationController
                 'adfs-idp-remote' => Translate::noop('ADFS IdP metadata'),
                 'adfs-idp-hosted' => Translate::noop('ADFS IdP metadata'),
             ],
-            'logouturl' => Auth::getAdminLogoutURL(),
+            'logouturl' => Utils\Auth::getAdminLogoutURL(),
         ];
 
         Module::callHooks('federationpage', $t);
@@ -174,7 +178,7 @@ class FederationController
                     }
                 } else {
                     $saml2entities['saml20-idp'] = $this->mdHandler->getMetaDataCurrent('saml20-idp-hosted');
-                    $saml2entities['saml20-idp']['url'] = \SimpleSAML\Utils\HTTP::getBaseURL().'saml2/idp/metadata.php';
+                    $saml2entities['saml20-idp']['url'] = Utils\HTTP::getBaseURL().'saml2/idp/metadata.php';
                     $saml2entities['saml20-idp']['metadata_array'] =
                         SAML2_IdP::getHostedMetadata(
                             $this->mdHandler->getMetaDataCurrentEntityID('saml20-idp-hosted')
@@ -189,7 +193,7 @@ class FederationController
                         $builder->addContact($contact['contactType'], $contact);
                     }
 
-                    $entity['metadata'] = \SimpleSAML\Metadata\Signer::sign(
+                    $entity['metadata'] = Signer::sign(
                         $builder->getEntityDescriptorText(),
                         $entity['metadata_array'],
                         'SAML 2 IdP'
@@ -197,7 +201,7 @@ class FederationController
                     $entities[$index] = $entity;
                 }
             } catch (\Exception $e) {
-                \SimpleSAML\Logger::error('Federation: Error loading saml20-idp: '.$e->getMessage());
+                Logger::error('Federation: Error loading saml20-idp: '.$e->getMessage());
             }
         }
 
@@ -216,7 +220,7 @@ class FederationController
                     }
                 } else {
                     $shib13entities['shib13-idp'] = $this->mdHandler->getMetaDataCurrent('shib13-idp-hosted');
-                    $shib13entities['shib13-idp']['url'] = \SimpleSAML\Utils\HTTP::getBaseURL().
+                    $shib13entities['shib13-idp']['url'] = Utils\HTTP::getBaseURL().
                         'shib13/idp/metadata.php';
                     $shib13entities['shib13-idp']['metadata_array'] =
                         SAML1_IdP::getHostedMetadata(
@@ -232,7 +236,7 @@ class FederationController
                         $builder->addContact($contact['contactType'], $contact);
                     }
 
-                    $entity['metadata'] = \SimpleSAML\Metadata\Signer::sign(
+                    $entity['metadata'] = Signer::sign(
                         $builder->getEntityDescriptorText(),
                         $entity['metadata_array'],
                         'SAML 2 SP'
@@ -240,7 +244,7 @@ class FederationController
                     $entities[$index] = $entity;
                 }
             } catch (\Exception $e) {
-                \SimpleSAML\Logger::error('Federation: Error loading shib13-idp: '.$e->getMessage());
+                Logger::error('Federation: Error loading shib13-idp: '.$e->getMessage());
             }
         }
 
@@ -274,7 +278,7 @@ class FederationController
                         $builder->addContact($contact['contactType'], $contact);
                     }
 
-                    $entity['metadata'] = \SimpleSAML\Metadata\Signer::sign(
+                    $entity['metadata'] = Signer::sign(
                         $builder->getEntityDescriptorText(),
                         $entity['metadata_array'],
                         'ADFS IdP'
@@ -282,7 +286,7 @@ class FederationController
                     $entities[$index] = $entity;
                 }
             } catch (\Exception $e) {
-                \SimpleSAML\Logger::error('Federation: Error loading adfs-idp: '.$e->getMessage());
+                Logger::error('Federation: Error loading adfs-idp: '.$e->getMessage());
             }
         }
 
@@ -328,7 +332,7 @@ class FederationController
         $entities = [];
 
         /** @var \SimpleSAML\Module\saml\Auth\Source\SP $source */
-        foreach (\SimpleSAML\Auth\Source::getSourcesOfType('saml:SP') as $source) {
+        foreach (Auth\Source::getSourcesOfType('saml:SP') as $source) {
             $metadata = $source->getHostedMetadata();
             if (isset($metadata['keys']) ) {
                 $certificates = $metadata['keys'];
@@ -363,7 +367,7 @@ class FederationController
             }
 
             // sign the metadata if enabled
-            $xml = \SimpleSAML\Metadata\Signer::sign($xml, $source->getMetadata()->toArray(), 'SAML 2 SP');
+            $xml = Signer::sign($xml, $source->getMetadata()->toArray(), 'SAML 2 SP');
 
             $entities[] = [
                 'authid' => $source->getAuthId(),
@@ -389,7 +393,7 @@ class FederationController
      */
     public function metadataConverter(Request $request)
     {
-        \SimpleSAML\Utils\Auth::requireAdmin();
+        Utils\Auth::requireAdmin();
 
         if ($xmlfile = $request->files->get('xmlfile')) {
             $xmldata = trim(file_get_contents($xmlfile));
@@ -398,8 +402,8 @@ class FederationController
         }
 
         if (!empty($xmldata)) {
-            \SimpleSAML\Utils\XML::checkSAMLMessage($xmldata, 'saml-meta');
-            $entities = \SimpleSAML\Metadata\SAMLParser::parseDescriptorsString($xmldata);
+            Utils\XML::checkSAMLMessage($xmldata, 'saml-meta');
+            $entities = SAMLParser::parseDescriptorsString($xmldata);
 
             // get all metadata for the entities
             foreach ($entities as &$entity) {
@@ -412,7 +416,7 @@ class FederationController
             }
 
             // transpose from $entities[entityid][type] to $output[type][entityid]
-            $output = \SimpleSAML\Utils\Arrays::transpose($entities);
+            $output = Utils\Arrays::transpose($entities);
 
             // merge all metadata of each type to a single string which should be added to the corresponding file
             foreach ($output as $type => &$entities) {
@@ -435,14 +439,14 @@ class FederationController
             $output = [];
         }
 
-        $t = new \SimpleSAML\XHTML\Template($this->config, 'admin:metadata_converter.twig');
+        $t = new Template($this->config, 'admin:metadata_converter.twig');
         $t->data = [
-            'logouturl' => \SimpleSAML\Utils\Auth::getAdminLogoutURL(),
+            'logouturl' => Utils\Auth::getAdminLogoutURL(),
             'xmldata' => $xmldata,
             'output' => $output,
         ];
 
-        $this->menu->addOption('logout', \SimpleSAML\Utils\Auth::getAdminLogoutURL(), Translate::noop('Log out'));
+        $this->menu->addOption('logout', $t->data['logouturl'], Translate::noop('Log out'));
         return $this->menu->insert($t);
     }
 }
diff --git a/modules/admin/lib/TestController.php b/modules/admin/lib/TestController.php
index be7a47033687b9992e23626a10ed78ea3a0407b0..957aca6c648d5cdb927fe3ecdb4eb25d8044b21a 100644
--- a/modules/admin/lib/TestController.php
+++ b/modules/admin/lib/TestController.php
@@ -2,9 +2,16 @@
 
 namespace SimpleSAML\Module\admin;
 
+use SAML2\Constants;
+use SAML2\XML\saml\NameID;
+use SimpleSAML\Auth;
+use SimpleSAML\Configuration;
 use SimpleSAML\HTTP\RunnableResponse;
 use SimpleSAML\Locale\Translate;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Module;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+use SimpleSAML\XHTML\Template;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
 
@@ -34,7 +41,7 @@ class TestController
      * @param \SimpleSAML\Configuration $config The configuration to use.
      * @param \SimpleSAML\Session $session The current user session.
      */
-    public function __construct(\SimpleSAML\Configuration $config, \SimpleSAML\Session $session)
+    public function __construct(Configuration $config, Session $session)
     {
         $this->config = $config;
         $this->session = $session;
@@ -50,25 +57,25 @@ class TestController
      */
     public function main(Request $request, $as)
     {
-        \SimpleSAML\Utils\Auth::requireAdmin();
+        Utils\Auth::requireAdmin();
         if (is_null($as)) {
-            $t = new \SimpleSAML\XHTML\Template($this->config, 'admin:authsource_list.twig');
+            $t = new Template($this->config, 'admin:authsource_list.twig');
             $t->data = [
-                'sources' => \SimpleSAML\Auth\Source::getSources(),
+                'sources' => Auth\Source::getSources(),
             ];
         } else {
-            $authsource = new \SimpleSAML\Auth\Simple($as);
+            $authsource = new Auth\Simple($as);
             if (!is_null($request->query->get('logout'))) {
                 $authsource->logout($this->config->getBasePath().'logout.php');
-            } elseif (!is_null($request->query->get(\SimpleSAML\Auth\State::EXCEPTION_PARAM))) {
+            } elseif (!is_null($request->query->get(Auth\State::EXCEPTION_PARAM))) {
                 // This is just a simple example of an error
-                $state = \SimpleSAML\Auth\State::loadExceptionState();
-                assert(array_key_exists(\SimpleSAML\Auth\State::EXCEPTION_DATA, $state));
-                throw $state[\SimpleSAML\Auth\State::EXCEPTION_DATA];
+                $state = Auth\State::loadExceptionState();
+                assert(array_key_exists(Auth\State::EXCEPTION_DATA, $state));
+                throw $state[Auth\State::EXCEPTION_DATA];
             }
 
             if (!$authsource->isAuthenticated()) {
-                $url = \SimpleSAML\Module::getModuleURL('admin/test/'.$as, []);
+                $url = Module::getModuleURL('admin/test/'.$as, []);
                 $params = [
                     'ErrorURL' => $url,
                     'ReturnTo' => $url,
@@ -80,13 +87,13 @@ class TestController
             $authData = $authsource->getAuthDataArray();
             $nameId = !is_null($authsource->getAuthData('saml:sp:NameID')) ? $authsource->getAuthData('saml:sp:NameID') : false;
 
-            $t = new \SimpleSAML\XHTML\Template($this->config, 'admin:status.twig', 'attributes');
+            $t = new Template($this->config, 'admin:status.twig', 'attributes');
             $t->data = [
                 'attributes' => $attributes,
                 'attributesHtml' => $this->getAttributesHTML($t, $attributes, ''),
                 'authData' => $authData,
                 'nameid' => $nameId,
-                'logouturl' => \SimpleSAML\Utils\HTTP::getSelfURLNoQuery().'?as='.urlencode($as).'&logout',
+                'logouturl' => Utils\HTTP::getSelfURLNoQuery().'?as='.urlencode($as).'&logout',
             ];
 
             if ($nameId !== false) {
@@ -94,8 +101,8 @@ class TestController
             }
         }
 
-        \SimpleSAML\Module::callHooks('configpage', $t);
-        $this->menu->addOption('logout', \SimpleSAML\Utils\Auth::getAdminLogoutURL(), Translate::noop('Log out'));
+        Module::callHooks('configpage', $t);
+        $this->menu->addOption('logout', Utils\Auth::getAdminLogoutURL(), Translate::noop('Log out'));
         return $this->menu->insert($t);
     }
 
@@ -105,7 +112,7 @@ class TestController
      * @param \SAML2\XML\saml\NameID $nameId
      * @return string
      */
-    private function getNameIDHTML(\SimpleSAML\XHTML\Template $t, \SAML2\XML\saml\NameID $nameId)
+    private function getNameIDHTML(Template $t, NameID $nameId)
     {
         $result = '';
         if ($nameId->getValue() === null) {
@@ -138,7 +145,7 @@ class TestController
      * @param string $nameParent
      * @return string
      */
-    private function getAttributesHTML(\SimpleSAML\XHTML\Template $t, $attributes, $nameParent)
+    private function getAttributesHTML(Template $t, $attributes, $nameParent)
     {
         $alternate = ['pure-table-odd', 'pure-table-even'];
         $i = 0;
@@ -188,10 +195,10 @@ class TestController
                         for ($idx = 0; $idx < $n; $idx++) {
                             $elem = $value[0]->item($idx);
                             /* @var \DOMElement $elem */
-                            if (!($elem->localName === 'NameID' && $elem->namespaceURI === \SAML2\Constants::NS_SAML)) {
+                            if (!($elem->localName === 'NameID' && $elem->namespaceURI === Constants::NS_SAML)) {
                                 continue;
                             }
-                            $str .= $this->present_eptid($trans, new \SAML2\XML\saml\NameID($elem));
+                            $str .= $this->present_eptid($trans, new NameID($elem));
                             break; // we only support one NameID here
                         }
                         $str .= '</td></tr>';
@@ -253,7 +260,7 @@ class TestController
      * @param \SAML2\XML\saml\NameID $nameID
      * @return string
      */
-    private function present_eptid(\SimpleSAML\Locale\Translate $t, \SAML2\XML\saml\NameID $nameID)
+    private function present_eptid(Translate $t, NameID $nameID)
     {
         $eptid = [
             'NameID' => [$nameID->getValue()],
diff --git a/modules/core/lib/ACL.php b/modules/core/lib/ACL.php
index 2c682a3e08d6bfa8aab90ae4eadcdee1f95e8fdf..b1da4993d92bd8ce0739e149080c21aaeb8d733d 100644
--- a/modules/core/lib/ACL.php
+++ b/modules/core/lib/ACL.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+
 /**
  * Generic library for access control lists.
  *
@@ -32,15 +35,15 @@ class ACL
 
         foreach ($acl as $rule) {
             if (!is_array($rule)) {
-                throw new \SimpleSAML\Error\Exception('Invalid rule in access control list: '.var_export($rule, true));
+                throw new Error\Exception('Invalid rule in access control list: '.var_export($rule, true));
             }
             if (count($rule) === 0) {
-                throw new \SimpleSAML\Error\Exception('Empty rule in access control list.');
+                throw new Error\Exception('Empty rule in access control list.');
             }
 
             $action = array_shift($rule);
             if ($action !== 'allow' && $action !== 'deny') {
-                throw new \SimpleSAML\Error\Exception(
+                throw new Error\Exception(
                     'Invalid action in rule in access control list: '.var_export($action, true)
                 );
             }
@@ -58,9 +61,9 @@ class ACL
     {
         assert(is_string($id));
 
-        $config = \SimpleSAML\Configuration::getOptionalConfig('acl.php');
+        $config = Configuration::getOptionalConfig('acl.php');
         if (!$config->hasValue($id)) {
-            throw new \SimpleSAML\Error\Exception('No ACL with id '.var_export($id, true).' in config/acl.php.');
+            throw new Error\Exception('No ACL with id '.var_export($id, true).' in config/acl.php.');
         }
 
         return $config->getArray($id);
@@ -121,7 +124,7 @@ class ACL
             case 'or':
                 return self::opOr($attributes, $rule);
             default:
-                throw new \SimpleSAML\Error\Exception('Invalid ACL operation: '.var_export($op, true));
+                throw new Error\Exception('Invalid ACL operation: '.var_export($op, true));
         }
     }
 
diff --git a/modules/core/lib/Auth/Process/AttributeAlter.php b/modules/core/lib/Auth/Process/AttributeAlter.php
index c8900822a025ac632cdd7e31289a0d8a2280fda4..a522facfc65c86fe194d7561b863e1f7d46e510e 100644
--- a/modules/core/lib/Auth/Process/AttributeAlter.php
+++ b/modules/core/lib/Auth/Process/AttributeAlter.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Error;
+
 /**
  * Filter to modify attributes using regular expressions
  *
@@ -64,7 +66,7 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter
                 } elseif ($value === '%remove') {
                     $this->remove = true;
                 } else {
-                    throw new \SimpleSAML\Error\Exception('Unknown flag : '.var_export($value, true));
+                    throw new Error\Exception('Unknown flag : '.var_export($value, true));
                 }
                 continue;
             } elseif ($name === 'pattern') {
@@ -102,20 +104,20 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter
 
         // check that all required params are set in config
         if (empty($this->pattern) || empty($this->subject)) {
-            throw new \SimpleSAML\Error\Exception("Not all params set in config.");
+            throw new Error\Exception("Not all params set in config.");
         }
 
         if (!$this->replace && !$this->remove && $this->replacement === false) {
-            throw new \SimpleSAML\Error\Exception("'replacement' must be set if neither '%replace' nor ".
+            throw new Error\Exception("'replacement' must be set if neither '%replace' nor ".
                 "'%remove' are set.");
         }
 
         if (!$this->replace && $this->replacement === null) {
-            throw new \SimpleSAML\Error\Exception("'%replace' must be set if 'replacement' is null.");
+            throw new Error\Exception("'%replace' must be set if 'replacement' is null.");
         }
 
         if ($this->replace && $this->remove) {
-            throw new \SimpleSAML\Error\Exception("'%replace' and '%remove' cannot be used together.");
+            throw new Error\Exception("'%replace' and '%remove' cannot be used together.");
         }
 
         if (empty($this->target)) {
@@ -124,7 +126,7 @@ class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter
         }
 
         if ($this->subject !== $this->target && $this->remove) {
-            throw new \SimpleSAML\Error\Exception("Cannot use '%remove' when 'target' is different than 'subject'.");
+            throw new Error\Exception("Cannot use '%remove' when 'target' is different than 'subject'.");
         }
 
         if (!array_key_exists($this->subject, $attributes)) {
diff --git a/modules/core/lib/Auth/Process/AttributeLimit.php b/modules/core/lib/Auth/Process/AttributeLimit.php
index f0789d9a2dda31346619b1d1af532caf53a8f67c..8559db4d68f261c791d48cb8f0a4acc4f27821e9 100644
--- a/modules/core/lib/Auth/Process/AttributeLimit.php
+++ b/modules/core/lib/Auth/Process/AttributeLimit.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+
 /**
  * A filter for limiting which attributes are passed on.
  *
@@ -41,18 +44,18 @@ class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter
                 $this->isDefault = (bool) $value;
             } elseif (is_int($index)) {
                 if (!is_string($value)) {
-                    throw new \SimpleSAML\Error\Exception('AttributeLimit: Invalid attribute name: '.
+                    throw new Error\Exception('AttributeLimit: Invalid attribute name: '.
                         var_export($value, true));
                 }
                 $this->allowedAttributes[] = $value;
             } elseif (is_string($index)) {
                 if (!is_array($value)) {
-                    throw new \SimpleSAML\Error\Exception('AttributeLimit: Values for '.
+                    throw new Error\Exception('AttributeLimit: Values for '.
                         var_export($index, true).' must be specified in an array.');
                 }
                 $this->allowedAttributes[$index] = $value;
             } else {
-                throw new \SimpleSAML\Error\Exception('AttributeLimit: Invalid option: '.var_export($index, true));
+                throw new Error\Exception('AttributeLimit: Invalid option: '.var_export($index, true));
             }
         }
     }
@@ -113,7 +116,7 @@ class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter
                 if (array_key_exists($name, $allowedAttributes)) {
                     // but it is an index of the array
                     if (!is_array($allowedAttributes[$name])) {
-                        throw new \SimpleSAML\Error\Exception('AttributeLimit: Values for '.
+                        throw new Error\Exception('AttributeLimit: Values for '.
                             var_export($name, true).' must be specified in an array.');
                     }
                     $attributes[$name] = $this->filterAttributeValues($attributes[$name], $allowedAttributes[$name]);
@@ -147,7 +150,7 @@ class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter
                      */
                     $regexResult = @preg_match($pattern, $attributeValue);
                     if ($regexResult === false) {
-                        \SimpleSAML\Logger::warning("Error processing regex '$pattern' on value '$attributeValue'");
+                        Logger::warning("Error processing regex '$pattern' on value '$attributeValue'");
                         break;
                     } elseif ($regexResult === 1) {
                         $matchedValues[] = $attributeValue;
diff --git a/modules/core/lib/Auth/Process/AttributeMap.php b/modules/core/lib/Auth/Process/AttributeMap.php
index 0a648dbccbfd5583545feb2cae627de0e48add48..db5bdbc4f54023d94afc8d59e984a9e2c299fc37 100644
--- a/modules/core/lib/Auth/Process/AttributeMap.php
+++ b/modules/core/lib/Auth/Process/AttributeMap.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Module;
+
 /**
  * Attribute filter for renaming attributes.
  *
@@ -76,15 +79,15 @@ class AttributeMap extends \SimpleSAML\Auth\ProcessingFilter
      */
     private function loadMapFile($fileName)
     {
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
 
         $m = explode(':', $fileName);
         if (count($m) === 2) {
             // we are asked for a file in a module
-            if (!\SimpleSAML\Module::isModuleEnabled($m[0])) {
+            if (!Module::isModuleEnabled($m[0])) {
                 throw new \Exception("Module '$m[0]' is not enabled.");
             }
-            $filePath = \SimpleSAML\Module::getModuleDir($m[0]).'/attributemap/'.$m[1].'.php';
+            $filePath = Module::getModuleDir($m[0]).'/attributemap/'.$m[1].'.php';
         } else {
             $filePath = $config->getPathValue('attributenamemapdir', 'attributemap/').$fileName.'.php';
         }
diff --git a/modules/core/lib/Auth/Process/AttributeValueMap.php b/modules/core/lib/Auth/Process/AttributeValueMap.php
index 189560f0bae0e0f2d66e8a8f6da6fc8ef6e12960..bf747b634baa89de8794891066ad7165aae653fc 100644
--- a/modules/core/lib/Auth/Process/AttributeValueMap.php
+++ b/modules/core/lib/Auth/Process/AttributeValueMap.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+
 /**
  * Filter to create target attribute based on value(s) in source attribute
  *
@@ -64,7 +67,7 @@ class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter
                     $this->keep = true;
                 } else {
                     // unknown configuration option, log it and ignore the error
-                    \SimpleSAML\Logger::warning(
+                    Logger::warning(
                         "AttributeValueMap: unknown configuration flag '".var_export($value, true)."'"
                     );
                 }
@@ -89,13 +92,13 @@ class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter
 
         // now validate it
         if (!is_string($this->sourceattribute)) {
-            throw new \SimpleSAML\Error\Exception("AttributeValueMap: 'sourceattribute' configuration option not set.");
+            throw new Error\Exception("AttributeValueMap: 'sourceattribute' configuration option not set.");
         }
         if (!is_string($this->targetattribute)) {
-            throw new \SimpleSAML\Error\Exception("AttributeValueMap: 'targetattribute' configuration option not set.");
+            throw new Error\Exception("AttributeValueMap: 'targetattribute' configuration option not set.");
         }
         if (!is_array($this->values)) {
-            throw new \SimpleSAML\Error\Exception("AttributeValueMap: 'values' configuration option is not an array.");
+            throw new Error\Exception("AttributeValueMap: 'values' configuration option is not an array.");
         }
     }
 
@@ -108,7 +111,7 @@ class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter
      */
     public function process(&$request)
     {
-        \SimpleSAML\Logger::debug('Processing the AttributeValueMap filter.');
+        Logger::debug('Processing the AttributeValueMap filter.');
 
         assert(is_array($request));
         assert(array_key_exists('Attributes', $request));
@@ -128,7 +131,7 @@ class AttributeValueMap extends \SimpleSAML\Auth\ProcessingFilter
                     $values = [$values];
                 }
                 if (count(array_intersect($values, $sourceattribute)) > 0) {
-                    \SimpleSAML\Logger::debug("AttributeValueMap: intersect match for '$value'");
+                    Logger::debug("AttributeValueMap: intersect match for '$value'");
                     $targetvalues[] = $value;
                 }
             }
diff --git a/modules/core/lib/Auth/Process/Cardinality.php b/modules/core/lib/Auth/Process/Cardinality.php
index 8e66ad93a7a8af6fa23c40092fec63068af149e4..b60fc389a816b7406b479baf522aa94f03222fc2 100644
--- a/modules/core/lib/Auth/Process/Cardinality.php
+++ b/modules/core/lib/Auth/Process/Cardinality.php
@@ -2,7 +2,11 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
-use SimpleSAML\Utils\HttpAdapter;
+use SimpleSAML\Auth;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
 
 /**
  * Filter to ensure correct cardinality of attributes
@@ -18,7 +22,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
     /** @var array Entities that should be ignored */
     private $ignoreEntities = [];
 
-    /** @var HTTPAdapter */
+    /** @var \SimpleSAML\Utils\HttpAdapter */
     private $http;
 
     /**
@@ -26,15 +30,15 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
      *
      * @param array &$config  Configuration information about this filter.
      * @param mixed $reserved  For future use.
-     * @param HTTPAdapter $http  HTTP utility service (handles redirects).
+     * @param \SimpleSAML\Utils\HttpAdapter $http  HTTP utility service (handles redirects).
      * @throws \SimpleSAML\Error\Exception
      */
-    public function __construct(&$config, $reserved, HttpAdapter $http = null)
+    public function __construct(&$config, $reserved, Utils\HttpAdapter $http = null)
     {
         parent::__construct($config, $reserved);
         assert(is_array($config));
 
-        $this->http = $http ? : new HttpAdapter();
+        $this->http = $http ? : new Utils\HttpAdapter();
 
         foreach ($config as $attribute => $rules) {
             if ($attribute === '%ignoreEntities') {
@@ -43,7 +47,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
             }
 
             if (!is_string($attribute)) {
-                throw new \SimpleSAML\Error\Exception('Invalid attribute name: '.var_export($attribute, true));
+                throw new Error\Exception('Invalid attribute name: '.var_export($attribute, true));
             }
             $this->cardinality[$attribute] = ['warn' => false];
 
@@ -68,20 +72,20 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
             } elseif (!is_int($this->cardinality[$attribute]['min']) ||
                 $this->cardinality[$attribute]['min'] < 0
             ) {
-                throw new \SimpleSAML\Error\Exception('Minimum cardinality must be a positive integer: '.
+                throw new Error\Exception('Minimum cardinality must be a positive integer: '.
                     var_export($attribute, true));
             }
             if (array_key_exists('max', $this->cardinality[$attribute]) &&
                 !is_int($this->cardinality[$attribute]['max'])
             ) {
-                throw new \SimpleSAML\Error\Exception('Maximum cardinality must be a positive integer: '.
+                throw new Error\Exception('Maximum cardinality must be a positive integer: '.
                     var_export($attribute, true));
             }
             if (array_key_exists('min', $this->cardinality[$attribute]) &&
                 array_key_exists('max', $this->cardinality[$attribute]) &&
                 $this->cardinality[$attribute]['min'] > $this->cardinality[$attribute]['max']
             ) {
-                throw new \SimpleSAML\Error\Exception('Minimum cardinality must be less than maximium: '.
+                throw new Error\Exception('Minimum cardinality must be less than maximium: '.
                     var_export($attribute, true));
             }
 
@@ -109,7 +113,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
             $entityid = $request['Source']['entityid'];
         }
         if (in_array($entityid, $this->ignoreEntities, true)) {
-            \SimpleSAML\Logger::debug('Cardinality: Ignoring assertions from '.$entityid);
+            Logger::debug('Cardinality: Ignoring assertions from '.$entityid);
             return;
         }
 
@@ -124,7 +128,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
             /* minimum cardinality */
             if (count($v) < $this->cardinality[$k]['min']) {
                 if ($this->cardinality[$k]['warn']) {
-                    \SimpleSAML\Logger::warning(
+                    Logger::warning(
                         sprintf(
                             'Cardinality: attribute %s from %s does not meet minimum cardinality of %d (%d)',
                             $k,
@@ -145,7 +149,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
             /* maximum cardinality */
             if (array_key_exists('max', $this->cardinality[$k]) && count($v) > $this->cardinality[$k]['max']) {
                 if ($this->cardinality[$k]['warn']) {
-                    \SimpleSAML\Logger::warning(
+                    Logger::warning(
                         sprintf(
                             'Cardinality: attribute %s from %s does not meet maximum cardinality of %d (%d)',
                             $k,
@@ -170,7 +174,7 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
                 continue;
             }
             if ($this->cardinality[$k]['warn']) {
-                \SimpleSAML\Logger::warning(sprintf(
+                Logger::warning(sprintf(
                     'Cardinality: attribute %s from %s is missing',
                     $k,
                     $entityid
@@ -185,8 +189,8 @@ class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
 
         /* abort if we found a problematic attribute */
         if (array_key_exists('core:cardinality:errorAttributes', $request)) {
-            $id = \SimpleSAML\Auth\State::saveState($request, 'core:cardinality');
-            $url = \SimpleSAML\Module::getModuleURL('core/cardinality_error.php');
+            $id = Auth\State::saveState($request, 'core:cardinality');
+            $url = Module::getModuleURL('core/cardinality_error.php');
             $this->http->redirectTrustedURL($url, ['StateId' => $id]);
             return;
         }
diff --git a/modules/core/lib/Auth/Process/CardinalitySingle.php b/modules/core/lib/Auth/Process/CardinalitySingle.php
index ca758adec8c0ec7ec95b2911212eb7e4ba11df89..13dad416bed83a371da51df9a9d2bc4819452f50 100644
--- a/modules/core/lib/Auth/Process/CardinalitySingle.php
+++ b/modules/core/lib/Auth/Process/CardinalitySingle.php
@@ -2,7 +2,10 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
-use SimpleSAML\Utils\HttpAdapter;
+use SimpleSAML\Auth;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
 
 /**
  * Filter to ensure correct cardinality of single-valued attributes
@@ -30,7 +33,7 @@ class CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter
     /** @var array Entities that should be ignored */
     private $ignoreEntities = [];
 
-    /** @var HTTPAdapter */
+    /** @var \SimpleSAML\Utils\HttpAdapter */
     private $http;
 
     /**
@@ -38,14 +41,14 @@ class CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter
      *
      * @param array &$config  Configuration information about this filter.
      * @param mixed $reserved  For future use.
-     * @param HTTPAdapter $http  HTTP utility service (handles redirects).
+     * @param \SimpleSAML\Utils\HttpAdapter $http  HTTP utility service (handles redirects).
      */
-    public function __construct(&$config, $reserved, HttpAdapter $http = null)
+    public function __construct(&$config, $reserved, Utils\HttpAdapter $http = null)
     {
         parent::__construct($config, $reserved);
         assert(is_array($config));
 
-        $this->http = $http ? : new HttpAdapter();
+        $this->http = $http ? : new Utils\HttpAdapter();
 
         if (array_key_exists('singleValued', $config)) {
             $this->singleValued = $config['singleValued'];
@@ -88,7 +91,7 @@ class CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter
             array_key_exists('entityid', $request['Source']) &&
             in_array($request['Source']['entityid'], $this->ignoreEntities, true)
         ) {
-            \SimpleSAML\Logger::debug('CardinalitySingle: Ignoring assertions from '.$request['Source']['entityid']);
+            Logger::debug('CardinalitySingle: Ignoring assertions from '.$request['Source']['entityid']);
             return;
         }
 
@@ -116,8 +119,8 @@ class CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter
 
         /* abort if we found a problematic attribute */
         if (array_key_exists('core:cardinality:errorAttributes', $request)) {
-            $id = \SimpleSAML\Auth\State::saveState($request, 'core:cardinality');
-            $url = \SimpleSAML\Module::getModuleURL('core/cardinality_error.php');
+            $id = Auth\State::saveState($request, 'core:cardinality');
+            $url = Module::getModuleURL('core/cardinality_error.php');
             $this->http->redirectTrustedURL($url, ['StateId' => $id]);
             return;
         }
diff --git a/modules/core/lib/Auth/Process/ExtendIdPSession.php b/modules/core/lib/Auth/Process/ExtendIdPSession.php
index adfa3fd1e547f2e5b560cd9c8f553001c02d9be7..7c6aa746a97dbc013e621dd40663abadb99229f4 100644
--- a/modules/core/lib/Auth/Process/ExtendIdPSession.php
+++ b/modules/core/lib/Auth/Process/ExtendIdPSession.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Session;
+use SimpleSAML\SessionHandler;
+
 /**
  * Extend IdP session and cookies.
  */
@@ -22,7 +26,7 @@ class ExtendIdPSession extends \SimpleSAML\Auth\ProcessingFilter
         $now = time();
         $delta = $state['Expire'] - $now;
 
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
         $sessionDuration = $globalConfig->getInteger('session.duration', 28800); // 8*60*60
 
         // Extend only if half of session duration already passed
@@ -31,7 +35,7 @@ class ExtendIdPSession extends \SimpleSAML\Auth\ProcessingFilter
         }
 
         // Update authority expire time
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $session->setAuthorityExpire($state['Authority']);
 
         // Update session cookies duration
@@ -46,7 +50,7 @@ class ExtendIdPSession extends \SimpleSAML\Auth\ProcessingFilter
         }
 
         // Or if session lifetime is more than zero
-        $sessionHandler = \SimpleSAML\SessionHandler::getSessionHandler();
+        $sessionHandler = SessionHandler::getSessionHandler();
         $cookieParams = $sessionHandler->getCookieParams();
         if ($cookieParams['lifetime'] > 0) {
             $session->updateSessionCookies();
diff --git a/modules/core/lib/Auth/Process/GenerateGroups.php b/modules/core/lib/Auth/Process/GenerateGroups.php
index 0ea05f67cd36f7e29777e3af32b0a96222696370..b5d738e1df64a6c45d467a6ea10f881bd2f309e7 100644
--- a/modules/core/lib/Auth/Process/GenerateGroups.php
+++ b/modules/core/lib/Auth/Process/GenerateGroups.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Logger;
+
 /**
  * Filter to generate a groups attribute based on many of the attributes of the user.
  *
@@ -67,7 +69,7 @@ class GenerateGroups extends \SimpleSAML\Auth\ProcessingFilter
 
         foreach ($this->generateGroupsFrom as $name) {
             if (!array_key_exists($name, $attributes)) {
-                \SimpleSAML\Logger::debug('GenerateGroups - attribute \''.$name.'\' not found.');
+                Logger::debug('GenerateGroups - attribute \''.$name.'\' not found.');
                 // Attribute not present
                 continue;
             }
diff --git a/modules/core/lib/Auth/Process/LanguageAdaptor.php b/modules/core/lib/Auth/Process/LanguageAdaptor.php
index ebee8f1d775e458d1897677d2a43d08a29b3ca08..818b866a96c0d04215ddb5f1e48cdda2f1b6d355 100644
--- a/modules/core/lib/Auth/Process/LanguageAdaptor.php
+++ b/modules/core/lib/Auth/Process/LanguageAdaptor.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Locale\Language;
+use SimpleSAML\Logger;
+
 /**
  * Filter to set and get language settings from attributes.
  *
@@ -50,18 +53,18 @@ class LanguageAdaptor extends \SimpleSAML\Auth\ProcessingFilter
             $attrlang = $attributes[$this->langattr][0];
         }
 
-        $lang = \SimpleSAML\Locale\Language::getLanguageCookie();
+        $lang = Language::getLanguageCookie();
 
         if (isset($attrlang)) {
-            \SimpleSAML\Logger::debug('LanguageAdaptor: Language in attribute was set ['.$attrlang.']');
+            Logger::debug('LanguageAdaptor: Language in attribute was set ['.$attrlang.']');
         }
         if (isset($lang)) {
-            \SimpleSAML\Logger::debug('LanguageAdaptor: Language in session was set ['.$lang.']');
+            Logger::debug('LanguageAdaptor: Language in session was set ['.$lang.']');
         }
 
         if (isset($attrlang) && !isset($lang)) {
             // Language set in attribute but not in cookie - update cookie
-            \SimpleSAML\Locale\Language::setLanguageCookie($attrlang);
+            Language::setLanguageCookie($attrlang);
         } elseif (!isset($attrlang) && isset($lang)) {
             // Language set in cookie, but not in attribute. Update attribute
             $request['Attributes'][$this->langattr] = [$lang];
diff --git a/modules/core/lib/Auth/Process/PHP.php b/modules/core/lib/Auth/Process/PHP.php
index bf0504f52a570e2b6b6a79969f116ffd293b59ac..96eb1773b8b35a46e50247f92d09e7eb84fe2555 100644
--- a/modules/core/lib/Auth/Process/PHP.php
+++ b/modules/core/lib/Auth/Process/PHP.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Error;
+
 /**
  * Attribute filter for running arbitrary PHP code.
  *
@@ -33,7 +35,7 @@ class PHP extends \SimpleSAML\Auth\ProcessingFilter
         assert(is_array($config));
 
         if (!isset($config['code'])) {
-            throw new \SimpleSAML\Error\Exception("core:PHP: missing mandatory configuration option 'code'.");
+            throw new Error\Exception("core:PHP: missing mandatory configuration option 'code'.");
         }
         $this->code = (string) $config['code'];
     }
diff --git a/modules/core/lib/Auth/Process/ScopeAttribute.php b/modules/core/lib/Auth/Process/ScopeAttribute.php
index f86058c5768a94d3321eb3ec8a6db4af75d8afcd..22bfa90aa0a87ff17e3726c07a4bab98bbfa1707 100644
--- a/modules/core/lib/Auth/Process/ScopeAttribute.php
+++ b/modules/core/lib/Auth/Process/ScopeAttribute.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Configuration;
+
 /**
  * Add a scoped variant of an attribute.
  *
@@ -50,7 +52,7 @@ class ScopeAttribute extends \SimpleSAML\Auth\ProcessingFilter
         parent::__construct($config, $reserved);
         assert(is_array($config));
 
-        $cfg = \SimpleSAML\Configuration::loadFromArray($config, 'ScopeAttribute');
+        $cfg = Configuration::loadFromArray($config, 'ScopeAttribute');
 
         $this->scopeAttribute = $cfg->getString('scopeAttribute');
         $this->sourceAttribute = $cfg->getString('sourceAttribute');
diff --git a/modules/core/lib/Auth/Process/ScopeFromAttribute.php b/modules/core/lib/Auth/Process/ScopeFromAttribute.php
index 323fc0038a914083988b57a53bb05f1493615b4d..54c9aa4cbf02a1c6d84257763e088b19041bf25a 100644
--- a/modules/core/lib/Auth/Process/ScopeFromAttribute.php
+++ b/modules/core/lib/Auth/Process/ScopeFromAttribute.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+
 /**
  * Retrieve a scope from a source attribute and add it as a virtual target
  * attribute.
@@ -46,7 +49,7 @@ class ScopeFromAttribute extends \SimpleSAML\Auth\ProcessingFilter
         parent::__construct($config, $reserved);
         assert(is_array($config));
 
-        $cfg = \SimpleSAML\Configuration::loadFromArray($config, 'ScopeFromAttribute');
+        $cfg = Configuration::loadFromArray($config, 'ScopeFromAttribute');
         $this->targetAttribute = $cfg->getString('targetAttribute');
         $this->sourceAttribute = $cfg->getString('sourceAttribute');
     } // end constructor
@@ -85,10 +88,10 @@ class ScopeFromAttribute extends \SimpleSAML\Auth\ProcessingFilter
             $attributes[$this->targetAttribute] = [];
             $scope = substr($sourceAttrVal, $scopeIndex + 1);
             $attributes[$this->targetAttribute][] = $scope;
-            \SimpleSAML\Logger::debug('ScopeFromAttribute: Inserted new attribute '.
+            Logger::debug('ScopeFromAttribute: Inserted new attribute '.
                 $this->targetAttribute.', with scope '.$scope);
         } else {
-            \SimpleSAML\Logger::warning('ScopeFromAttribute: The configured source attribute '.
+            Logger::warning('ScopeFromAttribute: The configured source attribute '.
                 $this->sourceAttribute.' does not have a scope. Did not add attribute '.
                     $this->targetAttribute.'.');
         }
diff --git a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php
index 7d796eceec7d6e18282e8290fa02ca1fd957419a..bf920128d881b4245a27c7d1d61c37a87b8bf4ba 100644
--- a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php
+++ b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Logger;
+
 /**
  * Log a line in the STAT log with one attribute.
  *
@@ -90,10 +92,10 @@ class StatisticsWithAttribute extends \SimpleSAML\Auth\ProcessingFilter
 
         if (!array_key_exists('PreviousSSOTimestamp', $state)) {
             // The user hasn't authenticated with this SP earlier in this session
-            \SimpleSAML\Logger::stats($isPassive.$this->typeTag.'-first '.$dest.' '.$source.' '.$logAttribute);
+            Logger::stats($isPassive.$this->typeTag.'-first '.$dest.' '.$source.' '.$logAttribute);
         }
 
-        \SimpleSAML\Logger::stats($isPassive.$this->typeTag.' '.$dest.' '.$source.' '.$logAttribute);
+        Logger::stats($isPassive.$this->typeTag.' '.$dest.' '.$source.' '.$logAttribute);
     }
 
     /**
diff --git a/modules/core/lib/Auth/Process/TargetedID.php b/modules/core/lib/Auth/Process/TargetedID.php
index 46a6b04ff662cfe5c61b3b56722ab69b4de0065e..6c720d6ba530808692263cd4e28e0dc369a2b031 100644
--- a/modules/core/lib/Auth/Process/TargetedID.php
+++ b/modules/core/lib/Auth/Process/TargetedID.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SAML2\Constants;
+use SAML2\XML\saml\NameID;
+use SimpleSAML\Utils;
+
 /**
  * Filter to generate the eduPersonTargetedID attribute.
  *
@@ -103,7 +107,7 @@ class TargetedID extends \SimpleSAML\Auth\ProcessingFilter
         }
 
 
-        $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
+        $secretSalt = Utils\Config::getSecretSalt();
 
         if (array_key_exists('Source', $state)) {
             $srcID = self::getEntityId($state['Source']);
@@ -127,9 +131,9 @@ class TargetedID extends \SimpleSAML\Auth\ProcessingFilter
 
         if ($this->generateNameId) {
             // Convert the targeted ID to a SAML 2.0 name identifier element
-            $nameId = new \SAML2\XML\saml\NameID();
+            $nameId = new NameID();
             $nameId->setValue($uid);
-            $nameId->setFormat(\SAML2\Constants::NAMEID_PERSISTENT);
+            $nameId->setFormat(Constants::NAMEID_PERSISTENT);
 
             if (isset($state['Source']['entityid'])) {
                 $nameId->setNameQualifier($state['Source']['entityid']);
diff --git a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
index a2cbe71e80c0f24b5f914a14c0f7e15d3a182fa7..d79783e86ff9c08c3ada39ed957680aebf37e6ed 100644
--- a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
+++ b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
@@ -2,6 +2,11 @@
 
 namespace SimpleSAML\Module\core\Auth\Process;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
 /**
  * Give a warning to the user if we receive multiple requests in a short time.
  *
@@ -42,12 +47,12 @@ class WarnShortSSOInterval extends \SimpleSAML\Auth\ProcessingFilter
             $entityId = 'UNKNOWN';
         }
 
-        \SimpleSAML\Logger::warning('WarnShortSSOInterval: Only '.$timeDelta.
+        Logger::warning('WarnShortSSOInterval: Only '.$timeDelta.
             ' seconds since last SSO for this user from the SP '.var_export($entityId, true));
 
         // Save state and redirect
-        $id = \SimpleSAML\Auth\State::saveState($state, 'core:short_sso_interval');
-        $url = \SimpleSAML\Module::getModuleURL('core/short_sso_interval.php');
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, ['StateId' => $id]);
+        $id = Auth\State::saveState($state, 'core:short_sso_interval');
+        $url = Module::getModuleURL('core/short_sso_interval.php');
+        Utils\HTTP::redirectTrustedURL($url, ['StateId' => $id]);
     }
 }
diff --git a/modules/core/lib/Auth/Source/AdminPassword.php b/modules/core/lib/Auth/Source/AdminPassword.php
index 45ce4c2696bb2514f9b579fcdf29f8c4dbcc1431..931707dbbc3b4985be1b8a23203dfd13a9482025 100644
--- a/modules/core/lib/Auth/Source/AdminPassword.php
+++ b/modules/core/lib/Auth/Source/AdminPassword.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Auth\Source;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+
 /**
  * Authentication source which verifies the password against
  * the 'auth.adminpassword' configuration option.
@@ -46,19 +49,19 @@ class AdminPassword extends \SimpleSAML\Module\core\Auth\UserPassBase
         assert(is_string($username));
         assert(is_string($password));
 
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $adminPassword = $config->getString('auth.adminpassword', '123');
         if ($adminPassword === '123') {
             // We require that the user changes the password
-            throw new \SimpleSAML\Error\Error('NOTSET');
+            throw new Error\Error('NOTSET');
         }
 
         if ($username !== "admin") {
-            throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
+            throw new Error\Error('WRONGUSERPASS');
         }
 
         if (!\SimpleSAML\Utils\Crypto::pwValid($adminPassword, $password)) {
-            throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
+            throw new Error\Error('WRONGUSERPASS');
         }
         return ['user' => ['admin']];
     }
diff --git a/modules/core/lib/Auth/UserPassBase.php b/modules/core/lib/Auth/UserPassBase.php
index 2730c8cb007df717d35e9a34a830437ad0d424cc..2eb860bf3a98873180fb8f7fa294ce4c2f98783f 100644
--- a/modules/core/lib/Auth/UserPassBase.php
+++ b/modules/core/lib/Auth/UserPassBase.php
@@ -2,6 +2,14 @@
 
 namespace SimpleSAML\Module\core\Auth;
 
+use SAML2\Constants;
+use SimpleSAML\Auth;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+use SimpleSAML\Utils\HTTP;
+
 /**
  * Helper class for username/password authentication.
  *
@@ -104,7 +112,7 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source
         }
 
         // get the "remember me" config options
-        $sspcnf = \SimpleSAML\Configuration::getInstance();
+        $sspcnf = Configuration::getInstance();
         $this->rememberMeEnabled = $sspcnf->getBoolean('session.rememberme.enable', false);
         $this->rememberMeChecked = $sspcnf->getBoolean('session.rememberme.checked', false);
     }
@@ -206,11 +214,11 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source
         // doesn't define how the credentials are transferred, but Office 365
         // uses the Authorization header, so we will just use that in lieu of
         // other use cases.
-        if (isset($state['saml:Binding']) && $state['saml:Binding'] === \SAML2\Constants::BINDING_PAOS) {
+        if (isset($state['saml:Binding']) && $state['saml:Binding'] === Constants::BINDING_PAOS) {
             if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
-                \SimpleSAML\Logger::error("ECP AuthnRequest did not contain Basic Authentication header");
+                Logger::error("ECP AuthnRequest did not contain Basic Authentication header");
                 // TODO Return a SOAP fault instead of using the current binding?
-                throw new \SimpleSAML\Error\Error("WRONGUSERPASS");
+                throw new Error\Error("WRONGUSERPASS");
             }
 
             $username = $_SERVER['PHP_AUTH_USER'];
@@ -228,15 +236,15 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source
         }
 
         // Save the $state-array, so that we can restore it after a redirect
-        $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID);
+        $id = Auth\State::saveState($state, self::STAGEID);
 
         /*
          * Redirect to the login form. We include the identifier of the saved
          * state array as a parameter to the login form.
          */
-        $url = \SimpleSAML\Module::getModuleURL('core/loginuserpass.php');
+        $url = Module::getModuleURL('core/loginuserpass.php');
         $params = ['AuthState' => $id];
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
+        HTTP::redirectTrustedURL($url, $params);
 
         // The previous function never returns, so this code is never executed.
         assert(false);
@@ -278,11 +286,11 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source
         assert(is_string($password));
 
         // Here we retrieve the state array we saved in the authenticate-function.
-        $state = \SimpleSAML\Auth\State::loadState($authStateId, self::STAGEID);
+        $state = Auth\State::loadState($authStateId, self::STAGEID);
 
         // Retrieve the authentication source we are executing.
         assert(array_key_exists(self::AUTHID, $state));
-        $source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]);
+        $source = Auth\Source::getById($state[self::AUTHID]);
         if ($source === null) {
             throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]);
         }
@@ -296,17 +304,17 @@ abstract class UserPassBase extends \SimpleSAML\Auth\Source
         try {
             $attributes = $source->login($username, $password);
         } catch (\Exception $e) {
-            \SimpleSAML\Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.');
+            Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.');
             throw $e;
         }
 
-        \SimpleSAML\Logger::stats('User \''.$username.'\' successfully authenticated from '.$_SERVER['REMOTE_ADDR']);
+        Logger::stats('User \''.$username.'\' successfully authenticated from '.$_SERVER['REMOTE_ADDR']);
 
         // Save the attributes we received from the login-function in the $state-array
         assert(is_array($attributes));
         $state['Attributes'] = $attributes;
 
         // Return control to SimpleSAMLphp after successful authentication.
-        \SimpleSAML\Auth\Source::completeAuth($state);
+        Auth\Source::completeAuth($state);
     }
 }
diff --git a/modules/core/lib/Auth/UserPassOrgBase.php b/modules/core/lib/Auth/UserPassOrgBase.php
index 6eca0d095491f3c16d995fc0c487181a522e115a..3975ef2221ec84d1819e899590bca6824bd14969 100644
--- a/modules/core/lib/Auth/UserPassOrgBase.php
+++ b/modules/core/lib/Auth/UserPassOrgBase.php
@@ -2,6 +2,11 @@
 
 namespace SimpleSAML\Module\core\Auth;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Error;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
 /**
  * Helper class for username/password/organization authentication.
  *
@@ -208,11 +213,11 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source
         // We are going to need the authId in order to retrieve this authentication source later
         $state[self::AUTHID] = $this->authId;
 
-        $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID);
+        $id = Auth\State::saveState($state, self::STAGEID);
 
-        $url = \SimpleSAML\Module::getModuleURL('core/loginuserpassorg.php');
+        $url = Module::getModuleURL('core/loginuserpassorg.php');
         $params = ['AuthState' => $id];
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
+        Utils\HTTP::redirectTrustedURL($url, $params);
     }
 
 
@@ -267,11 +272,11 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source
         assert(is_string($organization));
 
         /* Retrieve the authentication state. */
-        $state = \SimpleSAML\Auth\State::loadState($authStateId, self::STAGEID);
+        $state = Auth\State::loadState($authStateId, self::STAGEID);
 
         /* Find authentication source. */
         assert(array_key_exists(self::AUTHID, $state));
-        $source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]);
+        $source = Auth\Source::getById($state[self::AUTHID]);
         if ($source === null) {
             throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]);
         }
@@ -285,7 +290,7 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source
             } else {
                 if ($orgMethod === 'force') {
                     /* The organization should be a part of the username, but isn't. */
-                    throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
+                    throw new Error\Error('WRONGUSERPASS');
                 }
             }
         }
@@ -298,7 +303,7 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source
         $state['PersistentAuthData'][] = self::ORGID;
 
         $state['Attributes'] = $attributes;
-        \SimpleSAML\Auth\Source::completeAuth($state);
+        Auth\Source::completeAuth($state);
     }
 
 
@@ -316,11 +321,11 @@ abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source
         assert(is_string($authStateId));
 
         /* Retrieve the authentication state. */
-        $state = \SimpleSAML\Auth\State::loadState($authStateId, self::STAGEID);
+        $state = Auth\State::loadState($authStateId, self::STAGEID);
 
         /* Find authentication source. */
         assert(array_key_exists(self::AUTHID, $state));
-        $source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]);
+        $source = Auth\Source::getById($state[self::AUTHID]);
         if ($source === null) {
             throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]);
         }
diff --git a/modules/core/lib/Controller.php b/modules/core/lib/Controller.php
index 8a4563f42df18c96261dab9a35344e64c8a01c7e..1d88454b0c1f791ea27aad4a13a0a3ecb0dd5ca6 100644
--- a/modules/core/lib/Controller.php
+++ b/modules/core/lib/Controller.php
@@ -2,9 +2,15 @@
 
 namespace SimpleSAML\Module\core;
 
-use SimpleSAML\Error\Exception;
+use SimpleSAML\Auth;
+use SimpleSAML\Auth\AuthenticationFactory;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
 use SimpleSAML\HTTP\RunnableResponse;
-
+use SimpleSAML\Module;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+use SimpleSAML\XHTML\Template;
 use Symfony\Component\HttpFoundation\RedirectResponse;
 use Symfony\Component\HttpFoundation\Request;
 
@@ -17,7 +23,6 @@ use Symfony\Component\HttpFoundation\Request;
  */
 class Controller
 {
-
     /** @var \SimpleSAML\Configuration */
     protected $config;
 
@@ -43,9 +48,9 @@ class Controller
      * @throws \Exception
      */
     public function __construct(
-        \SimpleSAML\Configuration $config,
-        \SimpleSAML\Session $session,
-        \SimpleSAML\Auth\AuthenticationFactory $factory
+        Configuration $config,
+        Session $session,
+        AuthenticationFactory $factory
     ) {
         $this->config = $config;
         $this->factory = $factory;
@@ -67,24 +72,24 @@ class Controller
     public function account($as)
     {
         if (!array_key_exists($as, $this->sources)) {
-            throw new Exception('Invalid authentication source');
+            throw new Error\Exception('Invalid authentication source');
         }
 
         $auth = $this->factory->create($as);
         if (!$auth->isAuthenticated()) {
             // not authenticated, start auth with specified source
-            return new RedirectResponse(\SimpleSAML\Module::getModuleURL('core/login/'.urlencode($as)));
+            return new RedirectResponse(Module::getModuleURL('core/login/'.urlencode($as)));
         }
 
         $attributes = $auth->getAttributes();
 
-        $t = new \SimpleSAML\XHTML\Template($this->config, 'auth_status.twig', 'attributes');
+        $t = new Template($this->config, 'auth_status.twig', 'attributes');
         $t->data['header'] = '{status:header_saml20_sp}';
         $t->data['attributes'] = $attributes;
         $t->data['nameid'] = !is_null($auth->getAuthData('saml:sp:NameID'))
             ? $auth->getAuthData('saml:sp:NameID')
             : false;
-        $t->data['logouturl'] = \SimpleSAML\Module::getModuleURL('core/logout/'.urlencode($as));
+        $t->data['logouturl'] = Module::getModuleURL('core/logout/'.urlencode($as));
         $t->data['remaining'] = $this->session->getAuthData($as, 'Expire') - time();
         $t->setStatusCode(200);
 
@@ -118,37 +123,37 @@ class Controller
         }
 
         if ($as === null) { // no authentication source specified
-            $t = new \SimpleSAML\XHTML\Template($this->config, 'core:login.twig');
-            $t->data['loginurl'] = \SimpleSAML\Utils\Auth::getAdminLoginURL();
+            $t = new Template($this->config, 'core:login.twig');
+            $t->data['loginurl'] = Utils\Auth::getAdminLoginURL();
             $t->data['sources'] = $this->sources;
             return $t;
         }
 
         // auth source defined, check if valid
         if (!array_key_exists($as, $this->sources)) {
-            throw new Exception('Invalid authentication source');
+            throw new Error\Exception('Invalid authentication source');
         }
 
         // at this point, we have a valid auth source selected, start auth
         $auth = $this->factory->create($as);
         $as = urlencode($as);
 
-        if ($request->get(\SimpleSAML\Auth\State::EXCEPTION_PARAM, false) !== false) {
+        if ($request->get(Auth\State::EXCEPTION_PARAM, false) !== false) {
             // This is just a simple example of an error
 
-            $state = \SimpleSAML\Auth\State::loadExceptionState();
-            assert(array_key_exists(\SimpleSAML\Auth\State::EXCEPTION_DATA, $state));
-            $e = $state[\SimpleSAML\Auth\State::EXCEPTION_DATA];
+            $state = Auth\State::loadExceptionState();
+            assert(array_key_exists(Auth\State::EXCEPTION_DATA, $state));
+            $e = $state[Auth\State::EXCEPTION_DATA];
 
             throw $e;
         }
 
         if ($auth->isAuthenticated()) {
-            return new RedirectResponse(\SimpleSAML\Module::getModuleURL('core/account/'.$as));
+            return new RedirectResponse(Module::getModuleURL('core/account/'.$as));
         }
 
         // we're not logged in, start auth
-        $url = \SimpleSAML\Module::getModuleURL('core/login/'.$as);
+        $url = Module::getModuleURL('core/login/'.$as);
         $params = array(
             'ErrorURL' => $url,
             'ReturnTo' => $url,
@@ -168,7 +173,7 @@ class Controller
      */
     public function logout($as)
     {
-        $auth = new \SimpleSAML\Auth\Simple($as);
+        $auth = new Auth\Simple($as);
         return new RunnableResponse([$auth, 'logout'], [$this->config->getBasePath().'logout.php']);
     }
 }
diff --git a/modules/core/lib/Stats/Output/File.php b/modules/core/lib/Stats/Output/File.php
index fb95e42e7382d6dea8b1d2a58dc39d6dee2d80a5..d3875afd13bd1f29c88aec391544784d7f9b409a 100644
--- a/modules/core/lib/Stats/Output/File.php
+++ b/modules/core/lib/Stats/Output/File.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Stats\Output;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+
 /**
  * Statistics logger that writes to a set of log files
  *
@@ -33,7 +36,7 @@ class File extends \SimpleSAML\Stats\Output
      *
      * @param \SimpleSAML\Configuration $config  The configuration for this output.
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         $this->logDir = $config->getPathValue('directory');
         if ($this->logDir === null) {
@@ -63,7 +66,7 @@ class File extends \SimpleSAML\Stats\Output
         $fileName = $this->logDir.'/'.$date.'.log';
         $this->file = @fopen($fileName, 'a');
         if ($this->file === false) {
-            throw new \SimpleSAML\Error\Exception('Error opening log file: '.var_export($fileName, true));
+            throw new Error\Exception('Error opening log file: '.var_export($fileName, true));
         }
 
         // Disable output buffering
diff --git a/modules/core/lib/Stats/Output/Log.php b/modules/core/lib/Stats/Output/Log.php
index d4919c5795cc2a02efb867e7b209e9df88828f00..0bf5603131d16d313ab419be952452835e797a23 100644
--- a/modules/core/lib/Stats/Output/Log.php
+++ b/modules/core/lib/Stats/Output/Log.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Stats\Output;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+
 /**
  * Statistics logger that writes to the default logging handler.
  *
@@ -22,10 +25,10 @@ class Log extends \SimpleSAML\Stats\Output
      * @param \SimpleSAML\Configuration $config  The configuration for this output.
      * @throws \Exception
      */
-    public function __construct(\SimpleSAML\Configuration $config)
+    public function __construct(Configuration $config)
     {
         $logLevel = $config->getString('level', 'notice');
-        $this->logger = ['\SimpleSAML\Logger', $logLevel];
+        $this->logger = [Logger::class, $logLevel];
         if (!is_callable($this->logger)) {
             throw new \Exception('Invalid log level: '.var_export($logLevel, true));
         }
diff --git a/modules/core/lib/Storage/SQLPermanentStorage.php b/modules/core/lib/Storage/SQLPermanentStorage.php
index 0650f7bf2ce9588e1905f0e11ca2f7ea9ad19d6b..bfbb4643725a502a8f326c2f2949a5aa46efc10f 100644
--- a/modules/core/lib/Storage/SQLPermanentStorage.php
+++ b/modules/core/lib/Storage/SQLPermanentStorage.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\core\Storage;
 
+use PDO;
+use SimpleSAML\Configuration;
+
 /**
  * SQLPermanentStorage
  *
@@ -26,7 +29,7 @@ class SQLPermanentStorage
     public function __construct($name, $config = null)
     {
         if (is_null($config)) {
-            $config = \SimpleSAML\Configuration::getInstance();
+            $config = Configuration::getInstance();
         }
 
         $datadir = $config->getPathValue('datadir', 'data/');
@@ -43,7 +46,7 @@ class SQLPermanentStorage
         }
 
         $dbfile = 'sqlite:'.$sqllitedir.$name.'.sqlite';
-        if ($this->db = new \PDO($dbfile)) {
+        if ($this->db = new PDO($dbfile)) {
             $q = @$this->db->query('SELECT key1 FROM data LIMIT 1');
             if ($q === false) {
                 $this->db->exec('
@@ -103,7 +106,7 @@ class SQLPermanentStorage
             ':updated' => time(), ':expire' => $expire,
             ':value' => serialize($value)];
         $prepared->execute($data);
-        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
         return $results;
     }
 
@@ -127,7 +130,7 @@ class SQLPermanentStorage
             ':type' => $type, ':updated' => time(),
             ':expire' => $expire, ':value' => serialize($value)];
         $prepared->execute($data);
-        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
         return $results;
     }
 
@@ -145,7 +148,7 @@ class SQLPermanentStorage
 
         $prepared = $this->db->prepare($query);
         $prepared->execute();
-        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
         if (count($results) !== 1) {
             return null;
         }
@@ -185,7 +188,7 @@ class SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $data = [':type' => $type, ':key1' => $key1, ':key2' => $key2];
         $prepared->execute($data);
-        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
         return (count($results) == 1);
     }
 
@@ -203,7 +206,7 @@ class SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $prepared->execute();
 
-        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
         if (count($results) == 0) {
             return null;
         }
@@ -234,7 +237,7 @@ class SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $data = ['whichKey' => $whichKey];
         $prepared->execute($data);
-        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
 
         if (count($results) == 0) {
             return null;
@@ -259,7 +262,7 @@ class SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $data = [':type' => $type, ':key1' => $key1, ':key2' => $key2];
         $prepared->execute($data);
-        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
         return (count($results) == 1);
     }
 
diff --git a/modules/cron/lib/Cron.php b/modules/cron/lib/Cron.php
index 5396a2cfe0762221ccac7836b6c90718bb16b1cd..9956a87d42880436e36d8c8d7ac52ba3b69321b2 100644
--- a/modules/cron/lib/Cron.php
+++ b/modules/cron/lib/Cron.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Module\cron;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+
 /**
  * Handles interactions with SSP's cron system/hooks.
  */
@@ -17,10 +21,10 @@ class Cron
      * @param \SimpleSAML\Configuration $cronconfig The cron configuration to use. If not specified defaults
      * to `config/module_cron.php`
      */
-    public function __construct(\SimpleSAML\Configuration $cronconfig = null)
+    public function __construct(Configuration $cronconfig = null)
     {
         if ($cronconfig == null) {
-            $cronconfig = \SimpleSAML\Configuration::getConfig('module_cron.php');
+            $cronconfig = Configuration::getConfig('module_cron.php');
         }
         $this->cronconfig = $cronconfig;
     }
@@ -43,10 +47,10 @@ class Cron
             'tag' => $tag,
         ];
 
-        \SimpleSAML\Module::callHooks('cron', $croninfo);
+        Module::callHooks('cron', $croninfo);
 
         foreach ($summary as $s) {
-            \SimpleSAML\Logger::debug('Cron - Summary: '.$s);
+            Logger::debug('Cron - Summary: '.$s);
         }
 
         return $croninfo;
diff --git a/modules/exampleauth/lib/Auth/Process/RedirectTest.php b/modules/exampleauth/lib/Auth/Process/RedirectTest.php
index e72c5459e197b7c03e3ec547206f4d5a224461e8..aa4109a75b7ac1fe0c8b525cf6a08ed330399ab3 100644
--- a/modules/exampleauth/lib/Auth/Process/RedirectTest.php
+++ b/modules/exampleauth/lib/Auth/Process/RedirectTest.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Module\exampleautth\Auth\Process;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
 /**
  * A simple processing filter for testing that redirection works as it should.
  *
@@ -23,8 +27,8 @@ class RedirectTest extends \SimpleSAML\Auth\ProcessingFilter
         $state['Attributes']['RedirectTest1'] = ['OK'];
 
         // Save state and redirect
-        $id = \SimpleSAML\Auth\State::saveState($state, 'exampleauth:redirectfilter-test');
-        $url = \SimpleSAML\Module::getModuleURL('exampleauth/redirecttest.php');
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, ['StateId' => $id]);
+        $id = Auth\State::saveState($state, 'exampleauth:redirectfilter-test');
+        $url = Module::getModuleURL('exampleauth/redirecttest.php');
+        Utils\HTTP::redirectTrustedURL($url, ['StateId' => $id]);
     }
 }
diff --git a/modules/exampleauth/lib/Auth/Source/External.php b/modules/exampleauth/lib/Auth/Source/External.php
index 409b4ea42b8f87ff02fd3023925844ef6f328249..1b37ad7a86a99c5df7accf94a1ec84ab1d51dac5 100644
--- a/modules/exampleauth/lib/Auth/Source/External.php
+++ b/modules/exampleauth/lib/Auth/Source/External.php
@@ -2,6 +2,11 @@
 
 namespace SimpleSAML\Module\exampleauth\Auth\Source;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Error;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
 /**
  * Example external authentication source.
  *
@@ -138,14 +143,14 @@ class External extends \SimpleSAML\Auth\Source
          * and restores it in another location, and thus bypasses steps in
          * the authentication process.
          */
-        $stateId = \SimpleSAML\Auth\State::saveState($state, 'exampleauth:External');
+        $stateId = Auth\State::saveState($state, 'exampleauth:External');
 
         /*
          * Now we generate a URL the user should return to after authentication.
          * We assume that whatever authentication page we send the user to has an
          * option to return the user to a specific page afterwards.
          */
-        $returnTo = \SimpleSAML\Module::getModuleURL('exampleauth/resume.php', [
+        $returnTo = Module::getModuleURL('exampleauth/resume.php', [
             'State' => $stateId,
         ]);
 
@@ -156,7 +161,7 @@ class External extends \SimpleSAML\Auth\Source
          * is also part of this module, but in a real example, this would likely be
          * the absolute URL of the login page for the site.
          */
-        $authPage = \SimpleSAML\Module::getModuleURL('exampleauth/authpage.php');
+        $authPage = Module::getModuleURL('exampleauth/authpage.php');
 
         /*
          * The redirect to the authentication page.
@@ -164,7 +169,7 @@ class External extends \SimpleSAML\Auth\Source
          * Note the 'ReturnTo' parameter. This must most likely be replaced with
          * the real name of the parameter for the login page.
          */
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($authPage, [
+        Utils\HTTP::redirectTrustedURL($authPage, [
             'ReturnTo' => $returnTo,
         ]);
 
@@ -193,26 +198,26 @@ class External extends \SimpleSAML\Auth\Source
          * it in the 'State' request parameter.
          */
         if (!isset($_REQUEST['State'])) {
-            throw new \SimpleSAML\Error\BadRequest('Missing "State" parameter.');
+            throw new Error\BadRequest('Missing "State" parameter.');
         }
 
         /*
          * Once again, note the second parameter to the loadState function. This must
          * match the string we used in the saveState-call above.
          */
-        $state = \SimpleSAML\Auth\State::loadState($_REQUEST['State'], 'exampleauth:External');
+        $state = Auth\State::loadState($_REQUEST['State'], 'exampleauth:External');
 
         /*
          * Now we have the $state-array, and can use it to locate the authentication
          * source.
          */
-        $source = \SimpleSAML\Auth\Source::getById($state['exampleauth:AuthID']);
+        $source = Auth\Source::getById($state['exampleauth:AuthID']);
         if ($source === null) {
             /*
              * The only way this should fail is if we remove or rename the authentication source
              * while the user is at the login page.
              */
-            throw new \SimpleSAML\Error\Exception('Could not find authentication source with id '.$state[self::AUTHID]);
+            throw new Error\Exception('Could not find authentication source with id '.$state[self::AUTHID]);
         }
 
         /*
@@ -221,7 +226,7 @@ class External extends \SimpleSAML\Auth\Source
          * change config/authsources.php while an user is logging in.
          */
         if (!($source instanceof self)) {
-            throw new \SimpleSAML\Error\Exception('Authentication source type changed.');
+            throw new Error\Exception('Authentication source type changed.');
         }
 
         /*
@@ -237,7 +242,7 @@ class External extends \SimpleSAML\Auth\Source
              * Here we simply throw an exception, but we could also redirect the user back to the
              * login page.
              */
-            throw new \SimpleSAML\Error\Exception('User not authenticated after login page.');
+            throw new Error\Exception('User not authenticated after login page.');
         }
 
         /*
@@ -246,7 +251,7 @@ class External extends \SimpleSAML\Auth\Source
          */
 
         $state['Attributes'] = $attributes;
-        \SimpleSAML\Auth\Source::completeAuth($state);
+        Auth\Source::completeAuth($state);
 
         /*
          * The completeAuth-function never returns, so we never get this far.
diff --git a/modules/exampleauth/lib/Auth/Source/StaticSource.php b/modules/exampleauth/lib/Auth/Source/StaticSource.php
index 607a2e4962c94518253d0df461372177e3d33149..7d196b62d92407021317ee53d022594477d1d28c 100644
--- a/modules/exampleauth/lib/Auth/Source/StaticSource.php
+++ b/modules/exampleauth/lib/Auth/Source/StaticSource.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\exampleauth\Auth\Source;
 
+use SimpleSAML\Utils;
+
 /**
  * Example authentication source.
  *
@@ -34,7 +36,7 @@ class StaticSource extends \SimpleSAML\Auth\Source
 
         // Parse attributes
         try {
-            $this->attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($config);
+            $this->attributes = Utils\Attributes::normalizeAttributesArray($config);
         } catch (\Exception $e) {
             throw new \Exception('Invalid attributes for authentication source '.
                 $this->authId.': '.$e->getMessage());
diff --git a/modules/exampleauth/lib/Auth/Source/UserPass.php b/modules/exampleauth/lib/Auth/Source/UserPass.php
index 19da260bbdfa201c7bb86907da5a806e5002801b..76adc8324f346f1594e9a631861b25fd3d324780 100644
--- a/modules/exampleauth/lib/Auth/Source/UserPass.php
+++ b/modules/exampleauth/lib/Auth/Source/UserPass.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\exampleauth\Auth\Source;
 
+use SimpleSAML\Error;
+use SimpleSAML\Utils;
+
 /**
  * Example authentication source - username & password.
  *
@@ -54,7 +57,7 @@ class UserPass extends \SimpleSAML\Module\core\Auth\UserPassBase
             $password = $userpass[1];
 
             try {
-                $attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes);
+                $attributes = Utils\Attributes::normalizeAttributesArray($attributes);
             } catch (\Exception $e) {
                 throw new \Exception('Invalid attributes for user '.$username.
                     ' in authentication source '.$this->authId.': '.$e->getMessage());
@@ -83,7 +86,7 @@ class UserPass extends \SimpleSAML\Module\core\Auth\UserPassBase
 
         $userpass = $username.':'.$password;
         if (!array_key_exists($userpass, $this->users)) {
-            throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
+            throw new Error\Error('WRONGUSERPASS');
         }
 
         return $this->users[$userpass];
diff --git a/modules/multiauth/lib/Auth/Source/MultiAuth.php b/modules/multiauth/lib/Auth/Source/MultiAuth.php
index 185ccb46b2ed5d80c6b7259d080fbb0f64e5d174..31e76b2022383afedc6208afc758221d9ac5c8bb 100644
--- a/modules/multiauth/lib/Auth/Source/MultiAuth.php
+++ b/modules/multiauth/lib/Auth/Source/MultiAuth.php
@@ -2,6 +2,13 @@
 
 namespace SimpleSAML\Module\multiauth\Auth\Source;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\Module;
+use SimpleSAML\Session;
+use SimpleSAML\Utils;
+
 /**
  * Authentication source which let the user chooses among a list of
  * other authentication sources
@@ -68,9 +75,9 @@ class MultiAuth extends \SimpleSAML\Auth\Source
             $this->preselect = $config['preselect'];
         }
 
-        $globalConfiguration = \SimpleSAML\Configuration::getInstance();
+        $globalConfiguration = Configuration::getInstance();
         $defaultLanguage = $globalConfiguration->getString('language.default', 'en');
-        $authsources = \SimpleSAML\Configuration::getConfig('authsources.php');
+        $authsources = Configuration::getConfig('authsources.php');
         $this->sources = [];
         foreach ($config['sources'] as $source => $info) {
             if (is_int($source)) {
@@ -132,17 +139,17 @@ class MultiAuth extends \SimpleSAML\Auth\Source
         $state[self::AUTHID] = $this->authId;
         $state[self::SOURCESID] = $this->sources;
 
-        if (!\array_key_exists('multiauth:preselect', $state) && is_string($this->preselect)) {
+        if (!array_key_exists('multiauth:preselect', $state) && is_string($this->preselect)) {
             $state['multiauth:preselect'] = $this->preselect;
         }
 
         // Save the $state array, so that we can restore if after a redirect
-        $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID);
+        $id = Auth\State::saveState($state, self::STAGEID);
 
         /* Redirect to the select source page. We include the identifier of the
          * saved state array as a parameter to the login form
          */
-        $url = \SimpleSAML\Module::getModuleURL('multiauth/selectsource.php');
+        $url = Module::getModuleURL('multiauth/selectsource.php');
         $params = ['AuthState' => $id];
 
         // Allows the user to specify the auth source to be used
@@ -150,7 +157,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source
             $params['source'] = $_GET['source'];
         }
 
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
+        Utils\HTTP::redirectTrustedURL($url, $params);
 
         // The previous function never returns, so this code is never executed
         assert(false);
@@ -175,7 +182,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source
         assert(is_string($authId));
         assert(is_array($state));
 
-        $as = \SimpleSAML\Auth\Source::getById($authId);
+        $as = Auth\Source::getById($authId);
         $valid_sources = array_map(
             /**
              * @param array $src
@@ -191,23 +198,23 @@ class MultiAuth extends \SimpleSAML\Auth\Source
         }
 
         // Save the selected authentication source for the logout process.
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $session->setData(
             self::SESSION_SOURCE,
             $state[self::AUTHID],
             $authId,
-            \SimpleSAML\Session::DATA_TIMEOUT_SESSION_END
+            Session::DATA_TIMEOUT_SESSION_END
         );
 
         try {
             $as->authenticate($state);
-        } catch (\SimpleSAML\Error\Exception $e) {
-            \SimpleSAML\Auth\State::throwException($state, $e);
+        } catch (Error\Exception $e) {
+            Auth\State::throwException($state, $e);
         } catch (\Exception $e) {
-            $e = new \SimpleSAML\Error\UnserializableException($e);
-            \SimpleSAML\Auth\State::throwException($state, $e);
+            $e = new Error\UnserializableException($e);
+            Auth\State::throwException($state, $e);
         }
-        \SimpleSAML\Auth\Source::completeAuth($state);
+        Auth\Source::completeAuth($state);
     }
 
 
@@ -225,10 +232,10 @@ class MultiAuth extends \SimpleSAML\Auth\Source
         assert(is_array($state));
 
         // Get the source that was used to authenticate
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $authId = $session->getData(self::SESSION_SOURCE, $this->authId);
 
-        $source = \SimpleSAML\Auth\Source::getById($authId);
+        $source = Auth\Source::getById($authId);
         if ($source === null) {
             throw new \Exception('Invalid authentication source during logout: '.$source);
         }
@@ -252,7 +259,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source
 
         $cookieName = 'multiauth_source_'.$this->authId;
 
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $params = [
             // We save the cookies for 90 days
             'lifetime' => 7776000, //60*60*24*90
@@ -261,7 +268,7 @@ class MultiAuth extends \SimpleSAML\Auth\Source
             'httponly' => false,
         ];
 
-        \SimpleSAML\Utils\HTTP::setCookie($cookieName, $source, $params, false);
+        Utils\HTTP::setCookie($cookieName, $source, $params, false);
     }
 
 
diff --git a/modules/portal/lib/Portal.php b/modules/portal/lib/Portal.php
index 3df6495b583b9db2d96925bc28e4355b485716d1..12ae42aa98112e2d069c059082f6bde1d5f49eb3 100644
--- a/modules/portal/lib/Portal.php
+++ b/modules/portal/lib/Portal.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Module\portal;
 
+use SimpleSAML\Configuration;
+use SimpleSAML\Module;
+use SimpleSAML\Locale\Translate;
+
 class Portal
 {
     /** @var array */
@@ -63,7 +67,7 @@ class Portal
     public function getLoginInfo($translator, $thispage)
     {
         $info = ['info' => '', 'translator' => $translator, 'thispage' => $thispage];
-        \SimpleSAML\Module::callHooks('portalLoginInfo', $info);
+        Module::callHooks('portalLoginInfo', $info);
         return $info['info'];
     }
 
@@ -74,8 +78,8 @@ class Portal
      */
     public function getMenu($thispage)
     {
-        $config = \SimpleSAML\Configuration::getInstance();
-        $t = new \SimpleSAML\Locale\Translate($config);
+        $config = Configuration::getInstance();
+        $t = new Translate($config);
         $tabset = $this->getTabset($thispage);
         $logininfo = $this->getLoginInfo($t, $thispage);
         $classes = 'tabset_tabs ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all';
diff --git a/modules/saml/lib/Auth/Process/AttributeNameID.php b/modules/saml/lib/Auth/Process/AttributeNameID.php
index c7439d1e80fabd76f2e02a1fa13001c5583f3c3a..939bcacdb91f5c1db2037c0ddfda4a28961d5681 100644
--- a/modules/saml/lib/Auth/Process/AttributeNameID.php
+++ b/modules/saml/lib/Auth/Process/AttributeNameID.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+
 /**
  * Authentication processing filter to create a NameID from an attribute.
  *
@@ -32,12 +35,12 @@ class AttributeNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         assert(is_array($config));
 
         if (!isset($config['Format'])) {
-            throw new \SimpleSAML\Error\Exception("AttributeNameID: Missing required option 'Format'.");
+            throw new Error\Exception("AttributeNameID: Missing required option 'Format'.");
         }
         $this->format = (string) $config['Format'];
 
         if (!isset($config['attribute'])) {
-            throw new \SimpleSAML\Error\Exception("AttributeNameID: Missing required option 'attribute'.");
+            throw new Error\Exception("AttributeNameID: Missing required option 'attribute'.");
         }
         $this->attribute = (string) $config['attribute'];
     }
@@ -53,14 +56,14 @@ class AttributeNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
     {
 
         if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Missing attribute '.var_export($this->attribute, true).
                 ' on user - not generating attribute NameID.'
             );
             return null;
         }
         if (count($state['Attributes'][$this->attribute]) > 1) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'More than one value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating attribute NameID.'
             );
@@ -70,7 +73,7 @@ class AttributeNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         $value = $value[0];
 
         if (empty($value)) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Empty value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating attribute NameID.'
             );
diff --git a/modules/saml/lib/Auth/Process/AuthnContextClassRef.php b/modules/saml/lib/Auth/Process/AuthnContextClassRef.php
index f579d2c5528802ed4e65c7e3afe8b0609f8e8693..c9330a8db1f5a2af5a594fe77948086aa57a5d70 100644
--- a/modules/saml/lib/Auth/Process/AuthnContextClassRef.php
+++ b/modules/saml/lib/Auth/Process/AuthnContextClassRef.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SimpleSAML\Error;
+
 /**
  * Filter for setting the AuthnContextClassRef in the response.
  *
@@ -31,7 +33,7 @@ class AuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter
         assert(is_array($config));
 
         if (!isset($config['AuthnContextClassRef'])) {
-            throw new \SimpleSAML\Error\Exception('Missing AuthnContextClassRef option in processing filter.');
+            throw new Error\Exception('Missing AuthnContextClassRef option in processing filter.');
         }
 
         $this->authnContextClassRef = (string) $config['AuthnContextClassRef'];
diff --git a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
index b7aa14698a55f5443b104c520737dd6862850d20..7fde9ab41c0b0d04d4ebbe47127b41988fffe138 100644
--- a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
+++ b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
@@ -2,6 +2,12 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SimpleSAML\Auth;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Module;
+use SimpleSAML\Utils;
+
 /**
  * Attribute filter to validate AuthnContextClassRef values.
  *
@@ -48,10 +54,10 @@ class ExpectedAuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter
 
         assert(is_array($config));
         if (empty($config['accepted'])) {
-            \SimpleSAML\Logger::error(
+            Logger::error(
                 'ExpectedAuthnContextClassRef: Configuration error. There is no accepted AuthnContextClassRef.'
             );
-            throw new \SimpleSAML\Error\Exception(
+            throw new Error\Exception(
                 'ExpectedAuthnContextClassRef: Configuration error. There is no accepted AuthnContextClassRef.'
             );
         }
@@ -92,15 +98,15 @@ class ExpectedAuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter
      */
     protected function unauthorized(&$request)
     {
-        \SimpleSAML\Logger::error(
+        Logger::error(
             'ExpectedAuthnContextClassRef: Invalid authentication context: '.$this->AuthnContextClassRef.
             '. Accepted values are: '.var_export($this->accepted, true)
         );
 
-        $id = \SimpleSAML\Auth\State::saveState($request, 'saml:ExpectedAuthnContextClassRef:unauthorized');
-        $url = \SimpleSAML\Module::getModuleURL(
+        $id = Auth\State::saveState($request, 'saml:ExpectedAuthnContextClassRef:unauthorized');
+        $url = Module::getModuleURL(
             'saml/sp/wrong_authncontextclassref.php'
         );
-        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, ['StateId' => $id]);
+        Utils\HTTP::redirectTrustedURL($url, ['StateId' => $id]);
     }
 }
diff --git a/modules/saml/lib/Auth/Process/FilterScopes.php b/modules/saml/lib/Auth/Process/FilterScopes.php
index 1478112be462d1a4956a16d818dbca8f61609faa..7427be412bb5e2b12cd2be4dbce5c313a8da58c7 100644
--- a/modules/saml/lib/Auth/Process/FilterScopes.php
+++ b/modules/saml/lib/Auth/Process/FilterScopes.php
@@ -3,6 +3,7 @@
 namespace SimpleSAML\Module\saml\Auth\Process;
 
 use SimpleSAML\Logger;
+use SimpleSAML\Utils;
 
 /**
  * Filter to remove attribute values which are not properly scoped.
@@ -67,7 +68,7 @@ class FilterScopes extends \SimpleSAML\Auth\ProcessingFilter
             $values = $request['Attributes'][$attribute];
             $newValues = [];
             foreach ($values as $value) {
-                $ep = \SimpleSAML\Utils\Config\Metadata::getDefaultEndpoint($request['Source']['SingleSignOnService']);
+                $ep = Utils\Config\Metadata::getDefaultEndpoint($request['Source']['SingleSignOnService']);
                 $loc = $ep['Location'];
                 $host = parse_url($loc, PHP_URL_HOST);
                 if ($host === null) {
diff --git a/modules/saml/lib/Auth/Process/NameIDAttribute.php b/modules/saml/lib/Auth/Process/NameIDAttribute.php
index 1ee6e5f421cd4faaed1fe65f346e64269b117f0c..e0522f53d608796dcbbc5a1a497b1c7415280e03 100644
--- a/modules/saml/lib/Auth/Process/NameIDAttribute.php
+++ b/modules/saml/lib/Auth/Process/NameIDAttribute.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SAML2\Constants;
+use SimpleSAML\Error;
+
 /**
  * Authentication processing filter to create an attribute from a NameID.
  *
@@ -88,7 +91,7 @@ class NameIDAttribute extends \SimpleSAML\Auth\ProcessingFilter
                     $ret[] = '%';
                     break;
                 default:
-                    throw new \SimpleSAML\Error\Exception('NameIDAttribute: Invalid replacement: "%'.$replacement.'"');
+                    throw new Error\Exception('NameIDAttribute: Invalid replacement: "%'.$replacement.'"');
             }
 
             $pos = $next + 2;
@@ -119,7 +122,7 @@ class NameIDAttribute extends \SimpleSAML\Auth\ProcessingFilter
         assert(!is_null($rep->getValue()));
         $rep->{'%'} = '%';
         if ($rep->getFormat() !== null) {
-            $rep->setFormat(\SAML2\Constants::NAMEID_UNSPECIFIED);
+            $rep->setFormat(Constants::NAMEID_UNSPECIFIED);
         }
         if ($rep->getNameQualifier() !== null) {
             $rep->setNameQualifier($state['Source']['entityid']);
diff --git a/modules/saml/lib/Auth/Process/PersistentNameID.php b/modules/saml/lib/Auth/Process/PersistentNameID.php
index a70c7493291050a32e215c20e888017d3ad4748b..a2fd9552f1f0deea7976397cb5cc8a51b7622e96 100644
--- a/modules/saml/lib/Auth/Process/PersistentNameID.php
+++ b/modules/saml/lib/Auth/Process/PersistentNameID.php
@@ -2,6 +2,11 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SAML2\Constants;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Utils;
+
 /**
  * Authentication processing filter to generate a persistent NameID.
  *
@@ -31,10 +36,10 @@ class PersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         parent::__construct($config, $reserved);
         assert(is_array($config));
 
-        $this->format = \SAML2\Constants::NAMEID_PERSISTENT;
+        $this->format = Constants::NAMEID_PERSISTENT;
 
         if (!isset($config['attribute'])) {
-            throw new \SimpleSAML\Error\Exception("PersistentNameID: Missing required option 'attribute'.");
+            throw new Error\Exception("PersistentNameID: Missing required option 'attribute'.");
         }
         $this->attribute = $config['attribute'];
     }
@@ -49,26 +54,26 @@ class PersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
     protected function getValue(array &$state)
     {
         if (!isset($state['Destination']['entityid'])) {
-            \SimpleSAML\Logger::warning('No SP entity ID - not generating persistent NameID.');
+            Logger::warning('No SP entity ID - not generating persistent NameID.');
             return null;
         }
         $spEntityId = $state['Destination']['entityid'];
 
         if (!isset($state['Source']['entityid'])) {
-            \SimpleSAML\Logger::warning('No IdP entity ID - not generating persistent NameID.');
+            Logger::warning('No IdP entity ID - not generating persistent NameID.');
             return null;
         }
         $idpEntityId = $state['Source']['entityid'];
 
         if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Missing attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
             return null;
         }
         if (count($state['Attributes'][$this->attribute]) > 1) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'More than one value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
@@ -78,14 +83,14 @@ class PersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         $uid = $uid[0];
 
         if (empty($uid)) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Empty value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
             return null;
         }
 
-        $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
+        $secretSalt = Utils\Config::getSecretSalt();
 
         $uidData = 'uidhashbase'.$secretSalt;
         $uidData .= strlen($idpEntityId).':'.$idpEntityId;
diff --git a/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php b/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php
index 7bf2e2f1bbc1043da516f141ae333f38dab0dbf7..284162462684075bf7a86533b71bd04fa15f2dd4 100644
--- a/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php
+++ b/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SAML2\Constants;
+use SimpleSAML\Logger;
+
 /**
  * Authentication processing filter to create the eduPersonTargetedID attribute from the persistent NameID.
  *
@@ -60,16 +63,14 @@ class PersistentNameID2TargetedID extends \SimpleSAML\Auth\ProcessingFilter
     public function process(&$state)
     {
         assert(is_array($state));
-
-        if (!isset($state['saml:NameID'][\SAML2\Constants::NAMEID_PERSISTENT])) {
-            \SimpleSAML\Logger::warning(
+        if (!isset($state['saml:NameID'][Constants::NAMEID_PERSISTENT])) {
+            Logger::warning(
                 'Unable to generate eduPersonTargetedID because no persistent NameID was available.'
             );
             return;
         }
-
         /** @var \SAML2\XML\saml\NameID $nameID */
-        $nameID = $state['saml:NameID'][\SAML2\Constants::NAMEID_PERSISTENT];
+        $nameID = $state['saml:NameID'][Constants::NAMEID_PERSISTENT];
 
         $state['Attributes'][$this->attribute] = [(!$this->nameId) ? $nameID->getValue() : $nameID];
     }
diff --git a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
index 172aace1c243957996a2c5677b49f49d7a1aff1b..c40851018b79f90f13fa7c39c69b0c31a27da558 100644
--- a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
+++ b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SAML2\Constants;
+use SimpleSAML\Error;
+use SimpleSAML\Logger;
+
 /**
  * Authentication processing filter to generate a persistent NameID.
  *
@@ -52,10 +56,10 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         parent::__construct($config, $reserved);
         assert(is_array($config));
 
-        $this->format = \SAML2\Constants::NAMEID_PERSISTENT;
+        $this->format = Constants::NAMEID_PERSISTENT;
 
         if (!isset($config['attribute'])) {
-            throw new \SimpleSAML\Error\Exception("PersistentNameID: Missing required option 'attribute'.");
+            throw new Error\Exception("PersistentNameID: Missing required option 'attribute'.");
         }
         $this->attribute = $config['attribute'];
 
@@ -85,7 +89,7 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
     {
 
         if (!isset($state['saml:NameIDFormat']) && !$this->allowUnspecified) {
-            \SimpleSAML\Logger::debug(
+            Logger::debug(
                 'SQLPersistentNameID: Request did not specify persistent NameID format, '.
                 'not generating persistent NameID.'
             );
@@ -99,7 +103,7 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         if (count($validNameIdFormats) && !in_array($this->format, $validNameIdFormats, true) &&
             !$this->allowDifferent
         ) {
-            \SimpleSAML\Logger::debug(
+            Logger::debug(
                 'SQLPersistentNameID: SP expects different NameID format ('.
                 implode(', ', $validNameIdFormats).'),  not generating persistent NameID.'
             );
@@ -107,26 +111,26 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         }
 
         if (!isset($state['Destination']['entityid'])) {
-            \SimpleSAML\Logger::warning('SQLPersistentNameID: No SP entity ID - not generating persistent NameID.');
+            Logger::warning('SQLPersistentNameID: No SP entity ID - not generating persistent NameID.');
             return null;
         }
         $spEntityId = $state['Destination']['entityid'];
 
         if (!isset($state['Source']['entityid'])) {
-            \SimpleSAML\Logger::warning('SQLPersistentNameID: No IdP entity ID - not generating persistent NameID.');
+            Logger::warning('SQLPersistentNameID: No IdP entity ID - not generating persistent NameID.');
             return null;
         }
         $idpEntityId = $state['Source']['entityid'];
 
         if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'SQLPersistentNameID: Missing attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
             return null;
         }
         if (count($state['Attributes'][$this->attribute]) > 1) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'SQLPersistentNameID: More than one value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
@@ -136,7 +140,7 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         $uid = $uid[0];
 
         if (empty($uid)) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'Empty value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
@@ -145,7 +149,7 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
 
         $value = \SimpleSAML\Module\saml\IdP\SQLNameID::get($idpEntityId, $spEntityId, $uid);
         if ($value !== null) {
-            \SimpleSAML\Logger::debug(
+            Logger::debug(
                 'SQLPersistentNameID: Found persistent NameID '.var_export($value, true).' for user '.
                 var_export($uid, true).'.'
             );
@@ -153,17 +157,17 @@ class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         }
 
         if ((!isset($state['saml:AllowCreate']) || !$state['saml:AllowCreate']) && !$this->alwaysCreate) {
-            \SimpleSAML\Logger::warning(
+            Logger::warning(
                 'SQLPersistentNameID: Did not find persistent NameID for user, and not allowed to create new NameID.'
             );
             throw new \SimpleSAML\Module\saml\Error(
-                \SAML2\Constants::STATUS_RESPONDER,
-                'urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy'
+                Constants::STATUS_RESPONDER,
+                Constants::STATUS_INVALID_NAMEID_POLICY
             );
         }
 
         $value = bin2hex(openssl_random_pseudo_bytes(20));
-        \SimpleSAML\Logger::debug(
+        Logger::debug(
             'SQLPersistentNameID: Created persistent NameID '.var_export($value, true).' for user '.
             var_export($uid, true).'.'
         );
diff --git a/modules/saml/lib/Auth/Process/TransientNameID.php b/modules/saml/lib/Auth/Process/TransientNameID.php
index b4a24de5ecc08fa5d1cc41d1561460f107c5a28b..8b069f491435f8412cb78f5acfb2d4577d18f334 100644
--- a/modules/saml/lib/Auth/Process/TransientNameID.php
+++ b/modules/saml/lib/Auth/Process/TransientNameID.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\saml\Auth\Process;
 
+use SAML2\Constants;
+use SimpleSAML\Utils;
+
 /**
  * Authentication processing filter to generate a transient NameID.
  *
@@ -21,7 +24,7 @@ class TransientNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
         parent::__construct($config, $reserved);
         assert(is_array($config));
 
-        $this->format = \SAML2\Constants::NAMEID_TRANSIENT;
+        $this->format = Constants::NAMEID_TRANSIENT;
     }
 
 
@@ -33,6 +36,6 @@ class TransientNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
      */
     protected function getValue(array &$state)
     {
-        return \SimpleSAML\Utils\Random::generateID();
+        return Utils\Random::generateID();
     }
 }
diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php
index 2c79d6712100774e7ccc4553a9f1ba45d6148093..b055e8b232c2745e8750eb1de8fd9342f01ba4f9 100644
--- a/modules/saml/lib/Auth/Source/SP.php
+++ b/modules/saml/lib/Auth/Source/SP.php
@@ -7,22 +7,19 @@ use SAML2\Binding;
 use SAML2\Constants;
 use SAML2\XML\saml\NameID;
 
-use SimpleSAML\Auth\ProcessingChain;
-use SimpleSAML\Auth\Source;
-use SimpleSAML\Auth\State;
+use SimpleSAML\Auth;
 use SimpleSAML\Configuration;
+use SimpleSAML\Error;
 use SimpleSAML\IdP;
 use SimpleSAML\Logger;
 use SimpleSAML\Metadata\MetaDataStorageHandler;
 use SimpleSAML\Module;
 use SimpleSAML\Session;
 use SimpleSAML\Store;
-use SimpleSAML\Utils\Arrays;
-use SimpleSAML\Utils\Config\Metadata;
-use SimpleSAML\Utils\Crypto;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Utils;
+use SimpleSAML\XML\Shib13;
 
-class SP extends Source
+class SP extends \SimpleSAML\Auth\Source
 {
     /**
      * The entity ID of this SP.
@@ -186,7 +183,7 @@ class SP extends Source
             $metadata['OrganizationDisplayName'] = $this->metadata->getLocalizedString('OrganizationDisplayName', $org);
             $metadata['OrganizationURL'] = $this->metadata->getLocalizedString('OrganizationURL', null);
             if ($metadata['OrganizationURL'] === null) {
-                throw new \SimpleSAML\Error\Exception(
+                throw new Error\Exception(
                     'If OrganizationName is set, OrganizationURL must also be set.'
                 );
             }
@@ -195,7 +192,7 @@ class SP extends Source
         // add contacts
         $contacts = $this->metadata->getArray('contact', []);
         foreach ($contacts as $contact) {
-            $metadata['contacts'][] = Metadata::getContact($contact);
+            $metadata['contacts'][] = Utils\Config\Metadata::getContact($contact);
         }
 
         // add technical contact
@@ -207,11 +204,11 @@ class SP extends Source
                 'name' => $globalConfig->getString('technicalcontact_name', null),
                 'contactType' => 'technical',
             ];
-            $metadata['contacts'][] = Metadata::getContact($contact);
+            $metadata['contacts'][] = Utils\Config\Metadata::getContact($contact);
         }
 
         // add certificate(s)
-        $certInfo = Crypto::loadPublicKey($this->metadata, false, 'new_');
+        $certInfo = Utils\Crypto::loadPublicKey($this->metadata, false, 'new_');
         $hasNewCert = false;
         if ($certInfo !== null && array_key_exists('certData', $certInfo)) {
             $hasNewCert = true;
@@ -232,7 +229,7 @@ class SP extends Source
             ];
         }
 
-        $certInfo = Crypto::loadPublicKey($this->metadata);
+        $certInfo = Utils\Crypto::loadPublicKey($this->metadata);
         if ($certInfo !== null && array_key_exists('certData', $certInfo)) {
             $metadata['keys'][] = [
                 'type' => 'X509Certificate',
@@ -291,7 +288,7 @@ class SP extends Source
         assert(is_string($entityId));
 
         if ($this->idp !== null && $this->idp !== $entityId) {
-            throw new \SimpleSAML\Error\Exception('Cannot retrieve metadata for IdP '.
+            throw new Error\Exception('Cannot retrieve metadata for IdP '.
                 var_export($entityId, true).' because it isn\'t a valid IdP for this SP.');
         }
 
@@ -314,7 +311,7 @@ class SP extends Source
         }
 
         // Not found
-        throw new \SimpleSAML\Error\Exception('Could not find the metadata of an IdP with entity ID '.
+        throw new Error\Exception('Could not find the metadata of an IdP with entity ID '.
             var_export($entityId, true));
     }
 
@@ -467,10 +464,10 @@ class SP extends Source
 
         $state['saml:idp'] = $idpEntityId;
 
-        $ar = new \SimpleSAML\XML\Shib13\AuthnRequest();
+        $ar = new Shib13\AuthnRequest();
         $ar->setIssuer($this->entityId);
 
-        $id = State::saveState($state, 'saml:sp:sso');
+        $id = Auth\State::saveState($state, 'saml:sp:sso');
         $ar->setRelayState($id);
 
         $useArtifact = $idpMetadata->getBoolean('saml1.useartifact', null);
@@ -488,7 +485,7 @@ class SP extends Source
 
         Logger::debug('Starting SAML 1 SSO to '.var_export($idpEntityId, true).
             ' from '.var_export($this->entityId, true).'.');
-        HTTP::redirectTrustedURL($url);
+        Utils\HTTP::redirectTrustedURL($url);
     }
 
 
@@ -502,7 +499,7 @@ class SP extends Source
     private function startSSO2(Configuration $idpMetadata, array $state)
     {
         if (isset($state['saml:ProxyCount']) && $state['saml:ProxyCount'] < 0) {
-            State::throwException(
+            Auth\State::throwException(
                 $state,
                 new Module\saml\Error\ProxyCountExceeded(Constants::STATUS_RESPONDER)
             );
@@ -518,9 +515,9 @@ class SP extends Source
 
         $accr = null;
         if ($idpMetadata->getString('AuthnContextClassRef', false)) {
-            $accr = Arrays::arrayize($idpMetadata->getString('AuthnContextClassRef'));
+            $accr = Utils\Arrays::arrayize($idpMetadata->getString('AuthnContextClassRef'));
         } else if (isset($state['saml:AuthnContextClassRef'])) {
-            $accr = Arrays::arrayize($state['saml:AuthnContextClassRef']);
+            $accr = Utils\Arrays::arrayize($state['saml:AuthnContextClassRef']);
         }
 
         if ($accr !== null) {
@@ -553,7 +550,7 @@ class SP extends Source
 
         if (isset($state['saml:NameID'])) {
             if (!is_array($state['saml:NameID']) && !is_a($state['saml:NameID'], NameID::class)) {
-                throw new \SimpleSAML\Error\Exception('Invalid value of $state[\'saml:NameID\'].');
+                throw new Error\Exception('Invalid value of $state[\'saml:NameID\'].');
             }
 
             $nameId = $state['saml:NameID'];
@@ -644,7 +641,7 @@ class SP extends Source
         // save IdP entity ID as part of the state
         $state['ExpectedIssuer'] = $idpMetadata->getString('entityid');
 
-        $id = State::saveState($state, 'saml:sp:sso', true);
+        $id = Auth\State::saveState($state, 'saml:sp:sso', true);
         $ar->setId($id);
 
         Logger::debug(
@@ -731,7 +728,7 @@ class SP extends Source
      */
     private function startDisco(array $state)
     {
-        $id = State::saveState($state, 'saml:sp:sso');
+        $id = Auth\State::saveState($state, 'saml:sp:sso');
 
         $discoURL = $this->discoURL;
         if ($discoURL === null) {
@@ -755,7 +752,7 @@ class SP extends Source
             $params['isPassive'] = 'true';
         }
 
-        HTTP::redirectTrustedURL($discoURL, $params);
+        Utils\HTTP::redirectTrustedURL($discoURL, $params);
     }
 
 
@@ -926,9 +923,9 @@ class SP extends Source
         }
 
         // save the state WITHOUT a restart URL, so that we don't try an IdP-initiated login if something goes wrong
-        $id = State::saveState($state, 'saml:proxy:invalid_idp', true);
+        $id = Auth\State::saveState($state, 'saml:proxy:invalid_idp', true);
         $url = Module::getModuleURL('saml/proxy/invalid_session.php');
-        HTTP::redirectTrustedURL($url, ['AuthState' => $id]);
+        Utils\HTTP::redirectTrustedURL($url, ['AuthState' => $id]);
         assert(false);
     }
 
@@ -969,7 +966,7 @@ class SP extends Source
         // Update session state
         $session = Session::getSessionFromRequest();
         $authId = $state['saml:sp:AuthId'];
-        $session->doLogin($authId, State::getPersistentAuthData($state));
+        $session->doLogin($authId, Auth\State::getPersistentAuthData($state));
 
         // resume the login process
         call_user_func($state['ReturnCallback'], $state);
@@ -996,7 +993,7 @@ class SP extends Source
             $state['Responder'] = $state['saml:proxy:reauthLogout:PrevResponder'];
         }
 
-        $sp = Source::getById($state['saml:sp:AuthId'], Module\saml\Auth\Source\SP::class);
+        $sp = Auth\Source::getById($state['saml:sp:AuthId'], Module\saml\Auth\Source\SP::class);
         /** @var \SimpleSAML\Module\saml\Auth\Source\SP $authSource */
         Logger::debug('Proxy: logging in again.');
         $sp->authenticate($state);
@@ -1017,7 +1014,7 @@ class SP extends Source
         assert(array_key_exists('saml:logout:NameID', $state));
         assert(array_key_exists('saml:logout:SessionIndex', $state));
 
-        $id = State::saveState($state, 'saml:slosent');
+        $id = Auth\State::saveState($state, 'saml:slosent');
 
         $idp = $state['saml:logout:IdP'];
         $nameId = $state['saml:logout:NameID'];
@@ -1120,7 +1117,7 @@ class SP extends Source
             $authProcState['saml:sp:SessionIndex'] = $state['saml:sp:SessionIndex'];
         }
 
-        $pc = new ProcessingChain($idpMetadataArray, $spMetadataArray, 'sp');
+        $pc = new Auth\ProcessingChain($idpMetadataArray, $spMetadataArray, 'sp');
         $pc->processState($authProcState);
 
         self::onProcessingCompleted($authProcState);
@@ -1163,9 +1160,9 @@ class SP extends Source
         assert(is_string($redirectTo));
 
         $session = Session::getSessionFromRequest();
-        $session->doLogin($authId, State::getPersistentAuthData($state));
+        $session->doLogin($authId, Auth\State::getPersistentAuthData($state));
 
-        HTTP::redirectUntrustedURL($redirectTo);
+        Utils\HTTP::redirectUntrustedURL($redirectTo);
     }
 
 
@@ -1185,7 +1182,7 @@ class SP extends Source
         $state = $authProcState['saml:sp:State'];
 
         $sourceId = $state['saml:sp:AuthId'];
-        $source = Source::getById($sourceId);
+        $source = Auth\Source::getById($sourceId);
         if ($source === null) {
             throw new \Exception('Could not find authentication source with id '.$sourceId);
         }
@@ -1204,6 +1201,6 @@ class SP extends Source
             self::handleUnsolicitedAuth($sourceId, $state, $redirectTo);
         }
 
-        Source::completeAuth($state);
+        Auth\Source::completeAuth($state);
     }
 }
diff --git a/modules/saml/lib/BaseNameIDGenerator.php b/modules/saml/lib/BaseNameIDGenerator.php
index 30f9470905fd54d5c0941f161a5f9fdd3c86ecc7..d199f28f97dd6918b5fbc73dd0995716ebd9ac61 100644
--- a/modules/saml/lib/BaseNameIDGenerator.php
+++ b/modules/saml/lib/BaseNameIDGenerator.php
@@ -2,6 +2,9 @@
 
 namespace SimpleSAML\Module\saml;
 
+use SAML2\XML\saml\NameID;
+use SimpleSAML\Logger;
+
 /**
  * Base filter for generating NameID values.
  *
@@ -92,7 +95,7 @@ abstract class BaseNameIDGenerator extends \SimpleSAML\Auth\ProcessingFilter
             return;
         }
 
-        $nameId = new \SAML2\XML\saml\NameID();
+        $nameId = new NameID();
         $nameId->setValue($value);
         $nameId->setFormat($this->format);
 
@@ -100,7 +103,7 @@ abstract class BaseNameIDGenerator extends \SimpleSAML\Auth\ProcessingFilter
             if (isset($state['IdPMetadata']['entityid'])) {
                 $nameId->setNameQualifier($state['IdPMetadata']['entityid']);
             } else {
-                \SimpleSAML\Logger::warning('No IdP entity ID, unable to set NameQualifier.');
+                Logger::warning('No IdP entity ID, unable to set NameQualifier.');
             }
         } elseif (is_string($this->nameQualifier)) {
             $nameId->setNameQualifier($this->nameQualifier);
@@ -110,7 +113,7 @@ abstract class BaseNameIDGenerator extends \SimpleSAML\Auth\ProcessingFilter
             if (isset($state['SPMetadata']['entityid'])) {
                 $nameId->setSPNameQualifier($state['SPMetadata']['entityid']);
             } else {
-                \SimpleSAML\Logger::warning('No SP entity ID, unable to set SPNameQualifier.');
+                Logger::warning('No SP entity ID, unable to set SPNameQualifier.');
             }
         } elseif (is_string($this->spNameQualifier)) {
             $nameId->setSPNameQualifier($this->spNameQualifier);
diff --git a/modules/saml/lib/Error.php b/modules/saml/lib/Error.php
index e45b846ff89c99987927d99907da775750c7a43d..5612b05520bcd8bded03242a14f6fcb5e64b6528 100644
--- a/modules/saml/lib/Error.php
+++ b/modules/saml/lib/Error.php
@@ -2,6 +2,8 @@
 
 namespace SimpleSAML\Module\saml;
 
+use SAML2\Constants;
+
 /**
  * Class for representing a SAML 2 error.
  *
@@ -114,16 +116,16 @@ class Error extends \SimpleSAML\Error\Exception
         // TODO: remove this branch in 2.0
         } elseif ($exception instanceof \SimpleSAML\Error\NoPassive) {
             $e = new self(
-                \SAML2\Constants::STATUS_RESPONDER,
-                \SAML2\Constants::STATUS_NO_PASSIVE,
+                Constants::STATUS_RESPONDER,
+                Constants::STATUS_NO_PASSIVE,
                 $exception->getMessage(),
                 $exception
             );
         // TODO: remove this branch in 2.0
         } elseif ($exception instanceof \SimpleSAML\Error\ProxyCountExceeded) {
             $e = new self(
-                \SAML2\Constants::STATUS_RESPONDER,
-                \SAML2\Constants::STATUS_PROXY_COUNT_EXCEEDED,
+                Constants::STATUS_RESPONDER,
+                Constants::STATUS_PROXY_COUNT_EXCEEDED,
                 $exception->getMessage(),
                 $exception
             );
@@ -156,11 +158,11 @@ class Error extends \SimpleSAML\Error\Exception
         $e = null;
 
         switch ($this->status) {
-            case \SAML2\Constants::STATUS_RESPONDER:
+            case Constants::STATUS_RESPONDER:
                 switch ($this->subStatus) {
-                    case \SAML2\Constants::STATUS_NO_PASSIVE:
+                    case Constants::STATUS_NO_PASSIVE:
                         $e = new \SimpleSAML\Module\saml\Error\NoPassive(
-                            \SAML2\Constants::STATUS_RESPONDER,
+                            Constants::STATUS_RESPONDER,
                             $this->statusMessage
                         );
                         break;
diff --git a/modules/saml/lib/IdP/SAML1.php b/modules/saml/lib/IdP/SAML1.php
index 5e78d48278a6bc7e63728120b41b60e2f88ab643..1254f0d169d41b291cfcaf3f4bfbdf7f81d7af06 100644
--- a/modules/saml/lib/IdP/SAML1.php
+++ b/modules/saml/lib/IdP/SAML1.php
@@ -2,10 +2,16 @@
 
 namespace SimpleSAML\Module\saml\IdP;
 
+use SimpleSAML\Auth;
 use SimpleSAML\Bindings\Shib13\HTTPPost;
-use SimpleSAML\Utils\Config\Metadata;
-use SimpleSAML\Utils\Crypto;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\IdP;
+use SimpleSAML\Logger;
+use SimpleSAML\Metadata\MetaDataStorageHandler;
+use SimpleSAML\Stats;
+use SimpleSAML\Utils;
+use SimpleSAML\XML\Shib13\AuthnResponse;
 
 /**
  * IdP implementation for SAML 1.1 protocol.
@@ -22,11 +28,11 @@ class SAML1
      * @return array
      * @throws \SimpleSAML\Error\Exception
      * @throws \SimpleSAML\Error\MetadataNotFound
-     * @throws \SimpleSAML_Error_Exception
+     * @throws \SimpleSAML\Error\Exception
      */
     public static function getHostedMetadata($entityid)
     {
-        $handler = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $handler = MetaDataStorageHandler::getMetadataHandler();
         $config = $handler->getMetaDataConfig($entityid, 'shib13-idp-hosted');
 
         $metadata = [
@@ -39,7 +45,7 @@ class SAML1
 
         // add certificates
         $keys = [];
-        $certInfo = Crypto::loadPublicKey($config, false, 'new_');
+        $certInfo = Utils\Crypto::loadPublicKey($config, false, 'new_');
         $hasNewCert = false;
         if ($certInfo !== null) {
             $keys[] = [
@@ -52,7 +58,7 @@ class SAML1
             $hasNewCert = true;
         }
 
-        $certInfo = Crypto::loadPublicKey($config, true);
+        $certInfo = Utils\Crypto::loadPublicKey($config, true);
         $keys[] = [
             'type' => 'X509Certificate',
             'signing' => true,
@@ -71,7 +77,7 @@ class SAML1
             );
 
             if (!$config->hasValue('OrganizationURL')) {
-                throw new \SimpleSAML\Error\Exception('If OrganizationName is set, OrganizationURL must also be set.');
+                throw new Error\Exception('If OrganizationName is set, OrganizationURL must also be set.');
             }
             $metadata['OrganizationURL'] = $config->getLocalizedString('OrganizationURL');
         }
@@ -86,7 +92,7 @@ class SAML1
             $metadata['EntityAttributes'] = $config->getArray('EntityAttributes');
 
             // check for entity categories
-            if (Metadata::isHiddenFromDiscovery($metadata)) {
+            if (Utils\Config\Metadata::isHiddenFromDiscovery($metadata)) {
                 $metadata['hide.from.discovery'] = true;
             }
         }
@@ -104,7 +110,7 @@ class SAML1
         }
 
         // add contact information
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
         $email = $globalConfig->getString('technicalcontact_email', false);
         if ($email && $email !== 'na@example.org') {
             $contact = [
@@ -112,7 +118,7 @@ class SAML1
                 'name' => $globalConfig->getString('technicalcontact_name', null),
                 'contactType' => 'technical',
             ];
-            $metadata['contacts'][] = Metadata::getContact($contact);
+            $metadata['contacts'][] = Utils\Config\Metadata::getContact($contact);
         }
 
         return $metadata;
@@ -134,23 +140,23 @@ class SAML1
 
         $spMetadata = $state["SPMetadata"];
         $spEntityId = $spMetadata['entityid'];
-        $spMetadata = \SimpleSAML\Configuration::loadFromArray(
+        $spMetadata = Configuration::loadFromArray(
             $spMetadata,
             '$metadata['.var_export($spEntityId, true).']'
         );
 
-        \SimpleSAML\Logger::info('Sending SAML 1.1 Response to '.var_export($spEntityId, true));
+        Logger::info('Sending SAML 1.1 Response to '.var_export($spEntityId, true));
 
         $attributes = $state['Attributes'];
         $shire = $state['saml:shire'];
         $target = $state['saml:target'];
 
-        $idp = \SimpleSAML\IdP::getByState($state);
+        $idp = IdP::getByState($state);
 
         $idpMetadata = $idp->getConfig();
 
-        $config = \SimpleSAML\Configuration::getInstance();
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $config = Configuration::getInstance();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
 
         $statsData = [
             'spEntityID' => $spEntityId,
@@ -160,10 +166,10 @@ class SAML1
         if (isset($state['saml:AuthnRequestReceivedAt'])) {
             $statsData['logintime'] = microtime(true) - $state['saml:AuthnRequestReceivedAt'];
         }
-        \SimpleSAML\Stats::log('saml:idp:Response', $statsData);
+        Stats::log('saml:idp:Response', $statsData);
 
         // Generate and send response.
-        $ar = new \SimpleSAML\XML\Shib13\AuthnResponse();
+        $ar = new AuthnResponse();
         $authnResponseXML = $ar->generate($idpMetadata, $spMetadata, $shire, $attributes);
 
         $httppost = new HTTPPost($config, $metadata);
@@ -177,7 +183,7 @@ class SAML1
      * @param \SimpleSAML\IdP $idp  The IdP we are receiving it for.
      * @return void
      */
-    public static function receiveAuthnRequest(\SimpleSAML\IdP $idp)
+    public static function receiveAuthnRequest(IdP $idp)
     {
         if (isset($_REQUEST['cookieTime'])) {
             $cookieTime = (int) $_REQUEST['cookieTime'];
@@ -186,17 +192,17 @@ class SAML1
                  * Less than five seconds has passed since we were
                  * here the last time. Cookies are probably disabled.
                  */
-                HTTP::checkSessionCookie(HTTP::getSelfURL());
+                Utils\HTTP::checkSessionCookie(Utils\HTTP::getSelfURL());
             }
         }
 
         if (!isset($_REQUEST['providerId'])) {
-            throw new \SimpleSAML\Error\BadRequest('Missing providerId parameter.');
+            throw new Error\BadRequest('Missing providerId parameter.');
         }
         $spEntityId = (string) $_REQUEST['providerId'];
 
         if (!isset($_REQUEST['shire'])) {
-            throw new \SimpleSAML\Error\BadRequest('Missing shire parameter.');
+            throw new Error\BadRequest('Missing shire parameter.');
         }
         $shire = (string) $_REQUEST['shire'];
 
@@ -206,11 +212,11 @@ class SAML1
             $target = null;
         }
 
-        \SimpleSAML\Logger::info(
+        Logger::info(
             'Shib1.3 - IdP.SSOService: Got incoming Shib authnRequest from '.var_export($spEntityId, true).'.'
         );
 
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'shib13-sp-remote');
 
         $found = false;
@@ -230,7 +236,7 @@ class SAML1
             );
         }
 
-        \SimpleSAML\Stats::log(
+        Stats::log(
             'saml:idp:AuthnRequest',
             [
                 'spEntityID' => $spEntityId,
@@ -238,15 +244,15 @@ class SAML1
             ]
         );
 
-        $sessionLostURL = HTTP::addURLParameters(
-            HTTP::getSelfURL(),
+        $sessionLostURL = Utils\HTTP::addURLParameters(
+            Utils\HTTP::getSelfURL(),
             ['cookieTime' => time()]
         );
 
         $state = [
             'Responder' => ['\SimpleSAML\Module\saml\IdP\SAML1', 'sendResponse'],
             'SPMetadata' => $spMetadata->toArray(),
-            \SimpleSAML\Auth\State::RESTART => $sessionLostURL,
+            Auth\State::RESTART => $sessionLostURL,
             'saml:shire' => $shire,
             'saml:target' => $target,
             'saml:AuthnRequestReceivedAt' => microtime(true),
diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php
index aeece087423d2e99f2892b7c598f1d95ed8d3a91..f6cf7b5aa1e4e70bd2722e170fe7458dd22e0e9a 100644
--- a/modules/saml/lib/IdP/SAML2.php
+++ b/modules/saml/lib/IdP/SAML2.php
@@ -2,15 +2,35 @@
 
 namespace SimpleSAML\Module\saml\IdP;
 
+use DOMNodeList;
 use RobRichards\XMLSecLibs\XMLSecurityKey;
+use SAML2\Assertion;
+use SAML2\AuthnRequest;
+use SAML2\Binding;
 use SAML2\Constants;
+use SAML2\DOMDocumentFactory;
+use SAML2\EncryptedAssertion;
+use SAML2\HTTPRedirect;
+use SAML2\LogoutRequest;
+use SAML2\LogoutResponse;
+use SAML2\SOAP;
+use SAML2\XML\ds\X509Certificate;
+use SAML2\XML\ds\X509Data;
+use SAML2\XML\ds\KeyInfo;
+use SAML2\XML\saml\AttributeValue;
 use SAML2\XML\saml\Issuer;
+use SAML2\XML\saml\NameID;
+use SAML2\XML\saml\SubjectConfirmation;
+use SAML2\XML\saml\SubjectConfirmationData;
+use SimpleSAML\Auth;
 use SimpleSAML\Configuration;
+use SimpleSAML\Error;
+use SimpleSAML\IdP;
 use SimpleSAML\Logger;
-use SAML2\SOAP;
-use SimpleSAML\Utils\Config\Metadata;
-use SimpleSAML\Utils\Crypto;
-use SimpleSAML\Utils\HTTP;
+use SimpleSAML\Metadata\MetaDataStorageHandler;
+use SimpleSAML\Module;
+use SimpleSAML\Stats;
+use SimpleSAML\Utils;
 
 /**
  * IdP implementation for SAML 2.0 protocol.
@@ -47,7 +67,7 @@ class SAML2
         $consumerURL = $state['saml:ConsumerURL'];
         $protocolBinding = $state['saml:Binding'];
 
-        $idp = \SimpleSAML\IdP::getByState($state);
+        $idp = IdP::getByState($state);
 
         $idpMetadata = $idp->getConfig();
 
@@ -87,10 +107,10 @@ class SAML2
         if (isset($state['saml:AuthnRequestReceivedAt'])) {
             $statsData['logintime'] = microtime(true) - $state['saml:AuthnRequestReceivedAt'];
         }
-        \SimpleSAML\Stats::log('saml:idp:Response', $statsData);
+        Stats::log('saml:idp:Response', $statsData);
 
         // send the response
-        $binding = \SAML2\Binding::getBinding($protocolBinding);
+        $binding = Binding::getBinding($protocolBinding);
         $binding->send($ar);
     }
 
@@ -122,7 +142,7 @@ class SAML2
         $consumerURL = $state['saml:ConsumerURL'];
         $protocolBinding = $state['saml:Binding'];
 
-        $idp = \SimpleSAML\IdP::getByState($state);
+        $idp = IdP::getByState($state);
 
         $idpMetadata = $idp->getConfig();
 
@@ -151,9 +171,9 @@ class SAML2
         if (isset($state['saml:AuthnRequestReceivedAt'])) {
             $statsData['logintime'] = microtime(true) - $state['saml:AuthnRequestReceivedAt'];
         }
-        \SimpleSAML\Stats::log('saml:idp:Response:error', $statsData);
+        Stats::log('saml:idp:Response:error', $statsData);
 
-        $binding = \SAML2\Binding::getBinding($protocolBinding);
+        $binding = Binding::getBinding($protocolBinding);
         $binding->send($ar);
     }
 
@@ -171,7 +191,7 @@ class SAML2
      */
     private static function getAssertionConsumerService(
         array $supportedBindings,
-        \SimpleSAML\Configuration $spMetadata,
+        Configuration $spMetadata,
         $AssertionConsumerServiceURL,
         $ProtocolBinding,
         $AssertionConsumerServiceIndex
@@ -258,18 +278,18 @@ class SAML2
      */
     public static function receiveAuthnRequest(\SimpleSAML\IdP $idp)
     {
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $idpMetadata = $idp->getConfig();
 
-        $supportedBindings = [\SAML2\Constants::BINDING_HTTP_POST];
+        $supportedBindings = [Constants::BINDING_HTTP_POST];
         if ($idpMetadata->getBoolean('saml20.sendartifact', false)) {
-            $supportedBindings[] = \SAML2\Constants::BINDING_HTTP_ARTIFACT;
+            $supportedBindings[] = Constants::BINDING_HTTP_ARTIFACT;
         }
         if ($idpMetadata->getBoolean('saml20.hok.assertion', false)) {
-            $supportedBindings[] = \SAML2\Constants::BINDING_HOK_SSO;
+            $supportedBindings[] = Constants::BINDING_HOK_SSO;
         }
         if ($idpMetadata->getBoolean('saml20.ecp', false)) {
-            $supportedBindings[] = \SAML2\Constants::BINDING_PAOS;
+            $supportedBindings[] = Constants::BINDING_PAOS;
         }
 
         if (isset($_REQUEST['spentityid']) || isset($_REQUEST['providerId'])) {
@@ -282,7 +302,7 @@ class SAML2
                      * Less than five seconds has passed since we were
                      * here the last time. Cookies are probably disabled.
                      */
-                    \SimpleSAML\Utils\HTTP::checkSessionCookie(\SimpleSAML\Utils\HTTP::getSelfURL());
+                    Utils\HTTP::checkSessionCookie(Utils\HTTP::getSelfURL());
                 }
             }
 
@@ -335,18 +355,18 @@ class SAML2
                 'SAML2.0 - IdP.SSOService: IdP initiated authentication: '.var_export($spEntityId, true)
             );
         } else {
-            $binding = \SAML2\Binding::getCurrentBinding();
+            $binding = Binding::getCurrentBinding();
             $request = $binding->receive();
 
-            if (!($request instanceof \SAML2\AuthnRequest)) {
-                throw new \SimpleSAML\Error\BadRequest(
+            if (!($request instanceof AuthnRequest)) {
+                throw new Error\BadRequest(
                     'Message received on authentication request endpoint wasn\'t an authentication request.'
                 );
             }
 
             $issuer = $request->getIssuer();
             if ($issuer === null) {
-                throw new \SimpleSAML\Error\BadRequest(
+                throw new Error\BadRequest(
                     'Received message on authentication request endpoint without issuer.'
                 );
             } elseif ($issuer instanceof Issuer) {
@@ -394,7 +414,7 @@ class SAML2
             );
         }
 
-        \SimpleSAML\Stats::log('saml:idp:AuthnRequest', [
+        Stats::log('saml:idp:AuthnRequest', [
             'spEntityID'  => $spEntityId,
             'idpEntityID' => $idpMetadata->getString('entityid'),
             'forceAuthn'  => $forceAuthn,
@@ -432,18 +452,18 @@ class SAML2
         */
         $sessionLostParams['cookieTime'] = time();
 
-        $sessionLostURL = \SimpleSAML\Utils\HTTP::addURLParameters(
-            \SimpleSAML\Utils\HTTP::getSelfURLNoQuery(),
+        $sessionLostURL = Utils\HTTP::addURLParameters(
+            Utils\HTTP::getSelfURLNoQuery(),
             $sessionLostParams
         );
 
         $state = [
-            'Responder'                   => ['\SimpleSAML\Module\saml\IdP\SAML2', 'sendResponse'],
-            \SimpleSAML\Auth\State::EXCEPTION_HANDLER_FUNC => [
+            'Responder' => ['\SimpleSAML\Module\saml\IdP\SAML2', 'sendResponse'],
+            Auth\State::EXCEPTION_HANDLER_FUNC => [
                 '\SimpleSAML\Module\saml\IdP\SAML2',
                 'handleAuthError'
             ],
-            \SimpleSAML\Auth\State::RESTART => $sessionLostURL,
+            Auth\State::RESTART => $sessionLostURL,
 
             'SPMetadata'                  => $spMetadata->toArray(),
             'saml:RelayState'             => $relayState,
@@ -474,17 +494,17 @@ class SAML2
      * @param string|null     $relayState An id that should be carried across the logout.
      * @return void
      */
-    public static function sendLogoutRequest(\SimpleSAML\IdP $idp, array $association, $relayState)
+    public static function sendLogoutRequest(IdP $idp, array $association, $relayState)
     {
         assert(is_string($relayState) || $relayState === null);
 
         Logger::info('Sending SAML 2.0 LogoutRequest to: '.var_export($association['saml:entityID'], true));
 
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $idpMetadata = $idp->getConfig();
         $spMetadata = $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote');
 
-        \SimpleSAML\Stats::log('saml:idp:LogoutRequest:sent', [
+        Stats::log('saml:idp:LogoutRequest:sent', [
             'spEntityID'  => $association['saml:entityID'],
             'idpEntityID' => $idpMetadata->getString('entityid'),
         ]);
@@ -492,11 +512,11 @@ class SAML2
         $dst = $spMetadata->getEndpointPrioritizedByBinding(
             'SingleLogoutService',
             [
-                \SAML2\Constants::BINDING_HTTP_REDIRECT,
-                \SAML2\Constants::BINDING_HTTP_POST
+                Constants::BINDING_HTTP_REDIRECT,
+                Constants::BINDING_HTTP_POST
             ]
         );
-        $binding = \SAML2\Binding::getBinding($dst['Binding']);
+        $binding = Binding::getBinding($dst['Binding']);
         $lr = self::buildLogoutRequest($idpMetadata, $spMetadata, $association, $relayState);
         $lr->setDestination($dst['Location']);
 
@@ -511,7 +531,7 @@ class SAML2
      * @param array           &$state The logout state array.
      * @return void
      */
-    public static function sendLogoutResponse(\SimpleSAML\IdP $idp, array $state)
+    public static function sendLogoutResponse(IdP $idp, array $state)
     {
         assert(isset($state['saml:SPEntityId']));
         assert(isset($state['saml:RequestId']));
@@ -519,7 +539,7 @@ class SAML2
 
         $spEntityId = $state['saml:SPEntityId'];
 
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $idpMetadata = $idp->getConfig();
         $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');
 
@@ -530,8 +550,8 @@ class SAML2
         if (isset($state['core:Failed']) && $state['core:Failed']) {
             $partial = true;
             $lr->setStatus([
-                'Code'    => \SAML2\Constants::STATUS_SUCCESS,
-                'SubCode' => \SAML2\Constants::STATUS_PARTIAL_LOGOUT,
+                'Code'    => Constants::STATUS_SUCCESS,
+                'SubCode' => Constants::STATUS_PARTIAL_LOGOUT,
             ]);
             Logger::info('Sending logout response for partial logout to SP '.var_export($spEntityId, true));
         } else {
@@ -539,7 +559,7 @@ class SAML2
             Logger::debug('Sending logout response to SP '.var_export($spEntityId, true));
         }
 
-        \SimpleSAML\Stats::log('saml:idp:LogoutResponse:sent', [
+        Stats::log('saml:idp:LogoutResponse:sent', [
             'spEntityID'  => $spEntityId,
             'idpEntityID' => $idpMetadata->getString('entityid'),
             'partial'     => $partial
@@ -547,11 +567,11 @@ class SAML2
         $dst = $spMetadata->getEndpointPrioritizedByBinding(
             'SingleLogoutService',
             [
-                \SAML2\Constants::BINDING_HTTP_REDIRECT,
-                \SAML2\Constants::BINDING_HTTP_POST
+                Constants::BINDING_HTTP_REDIRECT,
+                Constants::BINDING_HTTP_POST
             ]
         );
-        $binding = \SAML2\Binding::getBinding($dst['Binding']);
+        $binding = Binding::getBinding($dst['Binding']);
         if (isset($dst['ResponseLocation'])) {
             $dst = $dst['ResponseLocation'];
         } else {
@@ -570,28 +590,28 @@ class SAML2
      * @return void
      * @throws \SimpleSAML\Error\BadRequest In case an error occurs while trying to receive the logout message.
      */
-    public static function receiveLogoutMessage(\SimpleSAML\IdP $idp)
+    public static function receiveLogoutMessage(IdP $idp)
     {
-        $binding = \SAML2\Binding::getCurrentBinding();
+        $binding = Binding::getCurrentBinding();
         $message = $binding->receive();
 
         $issuer = $message->getIssuer();
         if ($issuer === null) {
             /* Without an issuer we have no way to respond to the message. */
-            throw new \SimpleSAML\Error\BadRequest('Received message on logout endpoint without issuer.');
+            throw new Error\BadRequest('Received message on logout endpoint without issuer.');
         } elseif ($issuer instanceof Issuer) {
             $spEntityId = $issuer->getValue();
         } else {
             $spEntityId = $issuer;
         }
 
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $idpMetadata = $idp->getConfig();
         $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');
 
         \SimpleSAML\Module\saml\Message::validateMessage($spMetadata, $idpMetadata, $message);
 
-        if ($message instanceof \SAML2\LogoutResponse) {
+        if ($message instanceof LogoutResponse) {
             Logger::info('Received SAML 2.0 LogoutResponse from: '.var_export($spEntityId, true));
             $statsData = [
                 'spEntityID'  => $spEntityId,
@@ -600,7 +620,7 @@ class SAML2
             if (!$message->isSuccess()) {
                 $statsData['error'] = $message->getStatus();
             }
-            \SimpleSAML\Stats::log('saml:idp:LogoutResponse:recv', $statsData);
+            Stats::log('saml:idp:LogoutResponse:recv', $statsData);
 
             $relayState = $message->getRelayState();
 
@@ -614,9 +634,9 @@ class SAML2
             $assocId = 'saml:'.$spEntityId;
 
             $idp->handleLogoutResponse($assocId, $relayState, $logoutError);
-        } elseif ($message instanceof \SAML2\LogoutRequest) {
+        } elseif ($message instanceof LogoutRequest) {
             Logger::info('Received SAML 2.0 LogoutRequest from: '.var_export($spEntityId, true));
-            \SimpleSAML\Stats::log('saml:idp:LogoutRequest:recv', [
+            Stats::log('saml:idp:LogoutRequest:recv', [
                 'spEntityID'  => $spEntityId,
                 'idpEntityID' => $idpMetadata->getString('entityid'),
             ]);
@@ -634,7 +654,7 @@ class SAML2
             $assocId = 'saml:'.$spEntityId;
             $idp->handleLogoutRequest($state, $assocId);
         } else {
-            throw new \SimpleSAML\Error\BadRequest('Unknown message received on logout endpoint: '.get_class($message));
+            throw new Error\BadRequest('Unknown message received on logout endpoint: '.get_class($message));
         }
     }
 
@@ -648,34 +668,34 @@ class SAML2
      *
      * @return string The logout URL.
      */
-    public static function getLogoutURL(\SimpleSAML\IdP $idp, array $association, $relayState)
+    public static function getLogoutURL(IdP $idp, array $association, $relayState)
     {
         assert(is_string($relayState) || $relayState === null);
 
         Logger::info('Sending SAML 2.0 LogoutRequest to: '.var_export($association['saml:entityID'], true));
 
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         $idpMetadata = $idp->getConfig();
         $spMetadata = $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote');
 
         $bindings = [
-            \SAML2\Constants::BINDING_HTTP_REDIRECT,
-            \SAML2\Constants::BINDING_HTTP_POST
+            Constants::BINDING_HTTP_REDIRECT,
+            Constants::BINDING_HTTP_POST
         ];
         $dst = $spMetadata->getEndpointPrioritizedByBinding('SingleLogoutService', $bindings);
 
-        if ($dst['Binding'] === \SAML2\Constants::BINDING_HTTP_POST) {
+        if ($dst['Binding'] === Constants::BINDING_HTTP_POST) {
             $params = ['association' => $association['id'], 'idp' => $idp->getId()];
             if ($relayState !== null) {
                 $params['RelayState'] = $relayState;
             }
-            return \SimpleSAML\Module::getModuleURL('core/idp/logout-iframe-post.php', $params);
+            return Module::getModuleURL('core/idp/logout-iframe-post.php', $params);
         }
 
         $lr = self::buildLogoutRequest($idpMetadata, $spMetadata, $association, $relayState);
         $lr->setDestination($dst['Location']);
 
-        $binding = new \SAML2\HTTPRedirect();
+        $binding = new HTTPRedirect();
         return $binding->getRedirectURL($lr);
     }
 
@@ -688,9 +708,9 @@ class SAML2
      *
      * @return \SimpleSAML\Configuration  Configuration object for the SP metadata.
      */
-    public static function getAssociationConfig(\SimpleSAML\IdP $idp, array $association)
+    public static function getAssociationConfig(IdP $idp, array $association)
     {
-        $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $metadata = MetaDataStorageHandler::getMetadataHandler();
         try {
             return $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote');
         } catch (\Exception $e) {
@@ -711,7 +731,7 @@ class SAML2
      */
     public static function getHostedMetadata($entityid)
     {
-        $handler = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
+        $handler = MetaDataStorageHandler::getMetadataHandler();
         $config = $handler->getMetaDataConfig($entityid, 'saml20-idp-hosted');
 
         // configure endpoints
@@ -760,7 +780,7 @@ class SAML2
 
         // add certificates
         $keys = [];
-        $certInfo = Crypto::loadPublicKey($config, false, 'new_');
+        $certInfo = Utils\Crypto::loadPublicKey($config, false, 'new_');
         $hasNewCert = false;
         if ($certInfo !== null) {
             $keys[] = [
@@ -773,7 +793,7 @@ class SAML2
             $hasNewCert = true;
         }
 
-        $certInfo = Crypto::loadPublicKey($config, true);
+        $certInfo = Utils\Crypto::loadPublicKey($config, true);
         $keys[] = [
             'type' => 'X509Certificate',
             'signing' => true,
@@ -783,7 +803,7 @@ class SAML2
         ];
 
         if ($config->hasValue('https.certificate')) {
-            $httpsCert = Crypto::loadPublicKey($config, true, 'https.');
+            $httpsCert = Utils\Crypto::loadPublicKey($config, true, 'https.');
             $keys[] = [
                 'type' => 'X509Certificate',
                 'signing' => true,
@@ -799,7 +819,7 @@ class SAML2
             $metadata['ArtifactResolutionService'][] = [
                 'index' => 0,
                 'Binding' => Constants::BINDING_SOAP,
-                'Location' => HTTP::getBaseURL().'saml2/idp/ArtifactResolutionService.php'
+                'Location' => Utils\HTTP::getBaseURL().'saml2/idp/ArtifactResolutionService.php'
             ];
         }
 
@@ -810,7 +830,7 @@ class SAML2
                 [
                     'hoksso:ProtocolBinding' => Constants::BINDING_HTTP_REDIRECT,
                     'Binding' => Constants::BINDING_HOK_SSO,
-                    'Location' => HTTP::getBaseURL().'saml2/idp/SSOService.php',
+                    'Location' => Utils\HTTP::getBaseURL().'saml2/idp/SSOService.php',
                 ]
             );
         }
@@ -820,7 +840,7 @@ class SAML2
             $metadata['SingleSignOnService'][] = [
                 'index' => 0,
                 'Binding' => Constants::BINDING_SOAP,
-                'Location' => HTTP::getBaseURL().'saml2/idp/SSOService.php',
+                'Location' => Utils\HTTP::getBaseURL().'saml2/idp/SSOService.php',
             ];
         }
 
@@ -833,7 +853,7 @@ class SAML2
             );
 
             if (!$config->hasValue('OrganizationURL')) {
-                throw new \SimpleSAML\Error\Exception('If OrganizationName is set, OrganizationURL must also be set.');
+                throw new Error\Exception('If OrganizationName is set, OrganizationURL must also be set.');
             }
             $metadata['OrganizationURL'] = $config->getLocalizedString('OrganizationURL');
         }
@@ -848,7 +868,7 @@ class SAML2
             $metadata['EntityAttributes'] = $config->getArray('EntityAttributes');
 
             // check for entity categories
-            if (Metadata::isHiddenFromDiscovery($metadata)) {
+            if (Utils\Config\Metadata::isHiddenFromDiscovery($metadata)) {
                 $metadata['hide.from.discovery'] = true;
             }
         }
@@ -878,11 +898,11 @@ class SAML2
         if ($config->hasValue('contacts')) {
             $contacts = $config->getArray('contacts');
             foreach ($contacts as $contact) {
-                $metadata['contacts'][] = Metadata::getContact($contact);
+                $metadata['contacts'][] = Utils\Config\Metadata::getContact($contact);
             }
         }
 
-        $globalConfig = \SimpleSAML\Configuration::getInstance();
+        $globalConfig = Configuration::getInstance();
         $email = $globalConfig->getString('technicalcontact_email', false);
         if ($email && $email !== 'na@example.org') {
             $contact = [
@@ -890,7 +910,7 @@ class SAML2
                 'name' => $globalConfig->getString('technicalcontact_name', null),
                 'contactType' => 'technical',
             ];
-            $metadata['contacts'][] = Metadata::getContact($contact);
+            $metadata['contacts'][] = Utils\Config\Metadata::getContact($contact);
         }
 
         return $metadata;
@@ -924,7 +944,7 @@ class SAML2
                 $idpEntityId = $idpMetadata->getString('entityid');
                 $spEntityId = $spMetadata->getString('entityid');
 
-                $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
+                $secretSalt = Utils\Config::getSecretSalt();
 
                 $uidData = 'uidhashbase'.$secretSalt;
                 $uidData .= strlen($idpEntityId).':'.$idpEntityId;
@@ -1000,8 +1020,8 @@ class SAML2
                 }
 
                 $attrval = $value;
-                if ($value instanceof \DOMNodeList) {
-                    $attrval = new \SAML2\XML\saml\AttributeValue($value->item(0)->parentNode);
+                if ($value instanceof DOMNodeList) {
+                    $attrval = new AttributeValue($value->item(0)->parentNode);
                 }
 
                 switch ($encoding) {
@@ -1013,13 +1033,13 @@ class SAML2
                         break;
                     case 'raw':
                         if (is_string($value)) {
-                            $doc = \SAML2\DOMDocumentFactory::fromString('<root>'.$value.'</root>');
+                            $doc = DOMDocumentFactory::fromString('<root>'.$value.'</root>');
                             $value = $doc->firstChild->childNodes;
                         }
-                        assert($value instanceof \DOMNodeList || $value instanceof \SAML2\XML\saml\NameID);
+                        assert($value instanceof DOMNodeList || $value instanceof NameID);
                         break;
                     default:
-                        throw new \SimpleSAML\Error\Exception('Invalid encoding for attribute '.
+                        throw new Error\Exception('Invalid encoding for attribute '.
                             var_export($name, true).': '.var_export($encoding, true));
                 }
                 $ret[$name][] = $value;
@@ -1063,7 +1083,7 @@ class SAML2
         }
 
         // default
-        return 'urn:oasis:names:tc:SAML:2.0:attrname-format:basic';
+        return Constants::NAMEFORMAT_BASIC;
     }
 
 
@@ -1095,7 +1115,7 @@ class SAML2
 
         $config = Configuration::getInstance();
 
-        $a = new \SAML2\Assertion();
+        $a = new Assertion();
         if ($signAssertion) {
             \SimpleSAML\Module\saml\Message::addSign($idpMetadata, $spMetadata, $a);
         }
@@ -1116,10 +1136,10 @@ class SAML2
 
         if (isset($state['saml:AuthnContextClassRef'])) {
             $a->setAuthnContextClassRef($state['saml:AuthnContextClassRef']);
-        } elseif (\SimpleSAML\Utils\HTTP::isHTTPS()) {
-            $a->setAuthnContextClassRef(\SAML2\Constants::AC_PASSWORD_PROTECTED_TRANSPORT);
+        } elseif (Utils\HTTP::isHTTPS()) {
+            $a->setAuthnContextClassRef(Constants::AC_PASSWORD_PROTECTED_TRANSPORT);
         } else {
-            $a->setAuthnContextClassRef(\SAML2\Constants::AC_PASSWORD);
+            $a->setAuthnContextClassRef(Constants::AC_PASSWORD);
         }
 
         $sessionStart = $now;
@@ -1131,10 +1151,10 @@ class SAML2
         $sessionLifetime = $config->getInteger('session.duration', 8 * 60 * 60);
         $a->setSessionNotOnOrAfter($sessionStart + $sessionLifetime);
 
-        $a->setSessionIndex(\SimpleSAML\Utils\Random::generateID());
+        $a->setSessionIndex(Utils\Random::generateID());
 
-        $sc = new \SAML2\XML\saml\SubjectConfirmation();
-        $scd = new \SAML2\XML\saml\SubjectConfirmationData();
+        $sc = new SubjectConfirmation();
+        $scd = new SubjectConfirmationData();
         $scd->setNotOnOrAfter($now + $assertionLifetime);
         $scd->setRecipient($state['saml:ConsumerURL']);
         $scd->setInResponseTo($state['saml:RequestId']);
@@ -1142,7 +1162,7 @@ class SAML2
 
         // ProtcolBinding of SP's <AuthnRequest> overwrites IdP hosted metadata configuration
         $hokAssertion = null;
-        if ($state['saml:Binding'] === \SAML2\Constants::BINDING_HOK_SSO) {
+        if ($state['saml:Binding'] === Constants::BINDING_HOK_SSO) {
             $hokAssertion = true;
         }
         if ($hokAssertion === null) {
@@ -1151,43 +1171,43 @@ class SAML2
 
         if ($hokAssertion) {
             // Holder-of-Key
-            $sc->setMethod(\SAML2\Constants::CM_HOK);
-            if (\SimpleSAML\Utils\HTTP::isHTTPS()) {
+            $sc->setMethod(Constants::CM_HOK);
+            if (Utils\HTTP::isHTTPS()) {
                 if (isset($_SERVER['SSL_CLIENT_CERT']) && !empty($_SERVER['SSL_CLIENT_CERT'])) {
                     // extract certificate data (if this is a certificate)
                     $clientCert = $_SERVER['SSL_CLIENT_CERT'];
                     $pattern = '/^-----BEGIN CERTIFICATE-----([^-]*)^-----END CERTIFICATE-----/m';
                     if (preg_match($pattern, $clientCert, $matches)) {
                         // we have a client certificate from the browser which we add to the HoK assertion
-                        $x509Certificate = new \SAML2\XML\ds\X509Certificate();
+                        $x509Certificate = new X509Certificate();
                         $x509Certificate->setCertificate(str_replace(["\r", "\n", " "], '', $matches[1]));
 
-                        $x509Data = new \SAML2\XML\ds\X509Data();
+                        $x509Data = new X509Data();
                         $x509Data->addData($x509Certificate);
 
-                        $keyInfo = new \SAML2\XML\ds\KeyInfo();
+                        $keyInfo = new KeyInfo();
                         $keyInfo->addInfo($x509Data);
 
                         $scd->addInfo($keyInfo);
                     } else {
-                        throw new \SimpleSAML\Error\Exception(
+                        throw new Error\Exception(
                             'Error creating HoK assertion: No valid client certificate provided during TLS handshake '.
                             'with IdP'
                         );
                     }
                 } else {
-                    throw new \SimpleSAML\Error\Exception(
+                    throw new Error\Exception(
                         'Error creating HoK assertion: No client certificate provided during TLS handshake with IdP'
                     );
                 }
             } else {
-                throw new \SimpleSAML\Error\Exception(
+                throw new Error\Exception(
                     'Error creating HoK assertion: No HTTPS connection to IdP, but required for Holder-of-Key SSO'
                 );
             }
         } else {
             // Bearer
-            $sc->setMethod(\SAML2\Constants::CM_BEARER);
+            $sc->setMethod(Constants::CM_BEARER);
         }
         $sc->setSubjectConfirmationData($scd);
         $a->setSubjectConfirmation([$sc]);
@@ -1211,7 +1231,7 @@ class SAML2
             // either not set in request, or not set to a format we supply. Fall back to old generation method
             $nameIdFormat = current($spMetadata->getArrayizeString('NameIDFormat', []));
             if ($nameIdFormat === false) {
-                $nameIdFormat = current($idpMetadata->getArrayizeString('NameIDFormat', [\SAML2\Constants::NAMEID_TRANSIENT]));
+                $nameIdFormat = current($idpMetadata->getArrayizeString('NameIDFormat', [Constants::NAMEID_TRANSIENT]));
             }
         }
 
@@ -1224,21 +1244,21 @@ class SAML2
                 $spNameQualifier = $spMetadata->getString('entityid');
             }
 
-            if ($nameIdFormat === \SAML2\Constants::NAMEID_TRANSIENT) {
+            if ($nameIdFormat === Constants::NAMEID_TRANSIENT) {
                 // generate a random id
-                $nameIdValue = \SimpleSAML\Utils\Random::generateID();
+                $nameIdValue = Utils\Random::generateID();
             } else {
                 /* this code will end up generating either a fixed assigned id (via nameid.attribute)
                    or random id if not assigned/configured */
                 $nameIdValue = self::generateNameIdValue($idpMetadata, $spMetadata, $state);
                 if ($nameIdValue === null) {
                     Logger::warning('Falling back to transient NameID.');
-                    $nameIdFormat = \SAML2\Constants::NAMEID_TRANSIENT;
-                    $nameIdValue = \SimpleSAML\Utils\Random::generateID();
+                    $nameIdFormat = Constants::NAMEID_TRANSIENT;
+                    $nameIdValue = Utils\Random::generateID();
                 }
             }
 
-            $nameId = new \SAML2\XML\saml\NameID();
+            $nameId = new NameID();
             $nameId->setFormat($nameIdFormat);
             $nameId->setValue($nameIdValue);
             $nameId->setSPNameQualifier($spNameQualifier);
@@ -1277,7 +1297,7 @@ class SAML2
     private static function encryptAssertion(
         Configuration $idpMetadata,
         Configuration $spMetadata,
-        \SAML2\Assertion $assertion
+        Assertion $assertion
     ) {
         $encryptAssertion = $spMetadata->getBoolean('assertion.encryption', null);
         if ($encryptAssertion === null) {
@@ -1304,14 +1324,14 @@ class SAML2
                             "-----END CERTIFICATE-----\n";
                         break;
                     default:
-                        throw new \SimpleSAML\Error\Exception('Unsupported encryption key type: '.$key['type']);
+                        throw new Error\Exception('Unsupported encryption key type: '.$key['type']);
                 }
 
                 // extract the public key from the certificate for encryption
                 $key = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, ['type' => 'public']);
                 $key->loadKey($pemKey);
             } else {
-                throw new \SimpleSAML\Error\ConfigurationError(
+                throw new Error\ConfigurationError(
                     'Missing encryption key for entity `'.$spMetadata->getString('entityid').'`',
                     $spMetadata->getString('metadata-set').'.php',
                     null
@@ -1319,7 +1339,7 @@ class SAML2
             }
         }
 
-        $ea = new \SAML2\EncryptedAssertion();
+        $ea = new EncryptedAssertion();
         $ea->setAssertion($assertion, $key);
         return $ea;
     }
diff --git a/modules/saml/lib/IdP/SQLNameID.php b/modules/saml/lib/IdP/SQLNameID.php
index e62f77f0f76787b89500621397dbc74cec1b2aef..8ea3db41dc1d6bdbbe83e5d59afbcd83f5dce0eb 100644
--- a/modules/saml/lib/IdP/SQLNameID.php
+++ b/modules/saml/lib/IdP/SQLNameID.php
@@ -2,6 +2,10 @@
 
 namespace SimpleSAML\Module\saml\IdP;
 
+use PDO;
+use SimpleSAML\Error;
+use SimpleSAML\Store;
+
 /**
  * Helper class for working with persistent NameIDs stored in SQL datastore.
  *
@@ -15,7 +19,7 @@ class SQLNameID
      * @param \SimpleSAML\Store\SQL $store  The datastore.
      * @return void
      */
-    private static function createTable(\SimpleSAML\Store\SQL $store)
+    private static function createTable(Store\SQL $store)
     {
         if ($store->getTableVersion('saml_PersistentNameID') === 1) {
             return;
@@ -47,9 +51,9 @@ class SQLNameID
      */
     private static function getStore()
     {
-        $store = \SimpleSAML\Store::getInstance();
-        if (!($store instanceof \SimpleSAML\Store\SQL)) {
-            throw new \SimpleSAML\Error\Exception(
+        $store = Store::getInstance();
+        if (!($store instanceof Store\SQL)) {
+            throw new Error\Exception(
                 'SQL NameID store requires SimpleSAMLphp to be configured with a SQL datastore.'
             );
         }
@@ -120,7 +124,7 @@ class SQLNameID
         $query = $store->pdo->prepare($query);
         $query->execute($params);
 
-        $row = $query->fetch(\PDO::FETCH_ASSOC);
+        $row = $query->fetch(PDO::FETCH_ASSOC);
         if ($row === false) {
             // No NameID found
             return null;
@@ -184,7 +188,7 @@ class SQLNameID
         $query->execute($params);
 
         $res = [];
-        while (($row = $query->fetch(\PDO::FETCH_ASSOC)) !== false) {
+        while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== false) {
             $res[$row['_user']] = $row['_value'];
         }
 
diff --git a/modules/saml/lib/Message.php b/modules/saml/lib/Message.php
index c68a2647cb7f597db4ec2f8fa3b2ee8ac77bba7a..5ef132ed20b7491a0e8c2d589ba54529002c0cdd 100644
--- a/modules/saml/lib/Message.php
+++ b/modules/saml/lib/Message.php
@@ -3,8 +3,23 @@
 namespace SimpleSAML\Module\saml;
 
 use RobRichards\XMLSecLibs\XMLSecurityKey;
+use SAML2\Assertion;
+use SAML2\AuthnRequest;
 use SAML2\Constants;
+use SAML2\EncryptedAssertion;
+use SAML2\LogoutRequest;
+use SAML2\LogoutResponse;
+use SAML2\Response;
+use SAML2\SignedElement;
+use SAML2\StatusResponse;
+use SAML2\XML\ds\KeyInfo;
+use SAML2\XML\ds\X509Certificate;
+use SAML2\XML\ds\X509Data;
 use SAML2\XML\saml\Issuer;
+use SimpleSAML\Configuration;
+use SimpleSAML\Error as SSP_Error;
+use SimpleSAML\Logger;
+use SimpleSAML\Utils;
 
 /**
  * Common code for building SAML 2 messages based on the available metadata.
@@ -22,18 +37,18 @@ class Message
      * @return void
      */
     public static function addSign(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata,
-        \SAML2\SignedElement $element
+        Configuration $srcMetadata,
+        Configuration $dstMetadata,
+        SignedElement $element
     ) {
         $dstPrivateKey = $dstMetadata->getString('signature.privatekey', null);
 
         if ($dstPrivateKey !== null) {
-            $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, true, 'signature.');
-            $certArray = \SimpleSAML\Utils\Crypto::loadPublicKey($dstMetadata, false, 'signature.');
+            $keyArray = Utils\Crypto::loadPrivateKey($dstMetadata, true, 'signature.');
+            $certArray = Utils\Crypto::loadPublicKey($dstMetadata, false, 'signature.');
         } else {
-            $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($srcMetadata, true);
-            $certArray = \SimpleSAML\Utils\Crypto::loadPublicKey($srcMetadata, false);
+            $keyArray = Utils\Crypto::loadPrivateKey($srcMetadata, true);
+            $certArray = Utils\Crypto::loadPublicKey($srcMetadata, false);
         }
 
         $algo = $dstMetadata->getString('signature.algorithm', null);
@@ -72,18 +87,18 @@ class Message
      * @return void
      */
     private static function addRedirectSign(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata,
+        Configuration $srcMetadata,
+        Configuration $dstMetadata,
         \SAML2\Message $message
     ) {
 
         $signingEnabled = null;
-        if ($message instanceof \SAML2\LogoutRequest || $message instanceof \SAML2\LogoutResponse) {
+        if ($message instanceof LogoutRequest || $message instanceof LogoutResponse) {
             $signingEnabled = $srcMetadata->getBoolean('sign.logout', null);
             if ($signingEnabled === null) {
                 $signingEnabled = $dstMetadata->getBoolean('sign.logout', null);
             }
-        } elseif ($message instanceof \SAML2\AuthnRequest) {
+        } elseif ($message instanceof AuthnRequest) {
             $signingEnabled = $srcMetadata->getBoolean('sign.authnrequest', null);
             if ($signingEnabled === null) {
                 $signingEnabled = $dstMetadata->getBoolean('sign.authnrequest', null);
@@ -136,7 +151,7 @@ class Message
 
         $candidates = "'".implode("', '", $candidates)."'";
         $fps = "'".implode("', '", $certFingerprints)."'";
-        throw new \SimpleSAML\Error\Exception('Unable to find a certificate matching the configured '.
+        throw new SSP_Error\Exception('Unable to find a certificate matching the configured '.
             'fingerprint. Candidates: '.$candidates.'; certFingerprint: '.$fps.'.');
     }
 
@@ -151,7 +166,7 @@ class Message
      * @throws \SimpleSAML\Error\Exception if there is not certificate in the metadata for the entity.
      * @throws \Exception if the signature validation fails with an exception.
      */
-    public static function checkSign(\SimpleSAML\Configuration $srcMetadata, \SAML2\SignedElement $element)
+    public static function checkSign(Configuration $srcMetadata, SignedElement $element)
     {
         // find the public key that should verify signatures by this entity
         $keys = $srcMetadata->getPublicKeys('signing');
@@ -165,11 +180,11 @@ class Message
                             "-----END CERTIFICATE-----\n";
                         break;
                     default:
-                        \SimpleSAML\Logger::debug('Skipping unknown key type: '.$key['type']);
+                        Logger::debug('Skipping unknown key type: '.$key['type']);
                 }
             }
         } elseif ($srcMetadata->hasValue('certFingerprint')) {
-            \SimpleSAML\Logger::notice(
+            Logger::notice(
                 "Validating certificates by fingerprint is deprecated. Please use ".
                 "certData or certificate options in your remote metadata configuration."
             );
@@ -184,22 +199,22 @@ class Message
             // we don't have the full certificate stored. Try to find it in the message or the assertion instead
             if (count($certificates) === 0) {
                 /* We need the full certificate in order to match it against the fingerprint. */
-                \SimpleSAML\Logger::debug('No certificate in message when validating against fingerprint.');
+                Logger::debug('No certificate in message when validating against fingerprint.');
                 return false;
             } else {
-                \SimpleSAML\Logger::debug('Found '.count($certificates).' certificates in '.get_class($element));
+                Logger::debug('Found '.count($certificates).' certificates in '.get_class($element));
             }
 
             $pemCert = self::findCertificate($certFingerprint, $certificates);
             $pemKeys = [$pemCert];
         } else {
-            throw new \SimpleSAML\Error\Exception(
+            throw new SSP_Error\Exception(
                 'Missing certificate in metadata for '.
                 var_export($srcMetadata->getString('entityid'), true)
             );
         }
 
-        \SimpleSAML\Logger::debug('Has '.count($pemKeys).' candidate keys for validation.');
+        Logger::debug('Has '.count($pemKeys).' candidate keys for validation.');
 
         $lastException = null;
         foreach ($pemKeys as $i => $pem) {
@@ -210,12 +225,12 @@ class Message
                 // make sure that we have a valid signature on either the response or the assertion
                 $res = $element->validate($key);
                 if ($res) {
-                    \SimpleSAML\Logger::debug('Validation with key #'.$i.' succeeded.');
+                    Logger::debug('Validation with key #'.$i.' succeeded.');
                     return true;
                 }
-                \SimpleSAML\Logger::debug('Validation with key #'.$i.' failed without exception.');
+                Logger::debug('Validation with key #'.$i.' failed without exception.');
             } catch (\Exception $e) {
-                \SimpleSAML\Logger::debug('Validation with key #'.$i.' failed with exception: '.$e->getMessage());
+                Logger::debug('Validation with key #'.$i.' failed with exception: '.$e->getMessage());
                 $lastException = $e;
             }
         }
@@ -240,17 +255,17 @@ class Message
      * @throws \SimpleSAML\Error\Exception if message validation is enabled, but there is no signature in the message.
      */
     public static function validateMessage(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata,
+        Configuration $srcMetadata,
+        Configuration $dstMetadata,
         \SAML2\Message $message
     ) {
         $enabled = null;
-        if ($message instanceof \SAML2\LogoutRequest || $message instanceof \SAML2\LogoutResponse) {
+        if ($message instanceof LogoutRequest || $message instanceof LogoutResponse) {
             $enabled = $srcMetadata->getBoolean('validate.logout', null);
             if ($enabled === null) {
                 $enabled = $dstMetadata->getBoolean('validate.logout', null);
             }
-        } elseif ($message instanceof \SAML2\AuthnRequest) {
+        } elseif ($message instanceof AuthnRequest) {
             $enabled = $srcMetadata->getBoolean('validate.authnrequest', null);
             if ($enabled === null) {
                 $enabled = $dstMetadata->getBoolean('validate.authnrequest', null);
@@ -269,7 +284,7 @@ class Message
         }
 
         if (!self::checkSign($srcMetadata, $message)) {
-            throw new \SimpleSAML\Error\Exception(
+            throw new SSP_Error\Exception(
                 'Validation of received messages enabled, but no signature found on message.'
             );
         }
@@ -285,8 +300,8 @@ class Message
      * @return array Array of decryption keys.
      */
     public static function getDecryptionKeys(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata
+        Configuration $srcMetadata,
+        Configuration $dstMetadata
     ) {
         $sharedKey = $srcMetadata->getString('sharedkey', null);
         if ($sharedKey !== null) {
@@ -298,7 +313,7 @@ class Message
         $keys = [];
 
         // load the new private key if it exists
-        $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, false, 'new_');
+        $keyArray = Utils\Crypto::loadPrivateKey($dstMetadata, false, 'new_');
         if ($keyArray !== null) {
             assert(isset($keyArray['PEM']));
 
@@ -311,7 +326,7 @@ class Message
         }
 
         // find the existing private key
-        $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, true);
+        $keyArray = Utils\Crypto::loadPrivateKey($dstMetadata, true);
         assert(isset($keyArray['PEM']));
 
         $key = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, ['type' => 'private']);
@@ -336,8 +351,8 @@ class Message
      * @return array  Array of blacklisted algorithms.
      */
     public static function getBlacklistedAlgorithms(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata
+        Configuration $srcMetadata,
+        Configuration $dstMetadata
     ) {
         $blacklist = $srcMetadata->getArray('encryption.blacklisted-algorithms', null);
         if ($blacklist === null) {
@@ -361,13 +376,13 @@ class Message
      * @throws \Exception if decryption fails for whatever reason.
      */
     private static function decryptAssertion(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata,
+        Configuration $srcMetadata,
+        Configuration $dstMetadata,
         $assertion
     ) {
-        assert($assertion instanceof \SAML2\Assertion || $assertion instanceof \SAML2\EncryptedAssertion);
+        assert($assertion instanceof Assertion || $assertion instanceof EncryptedAssertion);
 
-        if ($assertion instanceof \SAML2\Assertion) {
+        if ($assertion instanceof Assertion) {
             $encryptAssertion = $srcMetadata->getBoolean('assertion.encryption', null);
             if ($encryptAssertion === null) {
                 $encryptAssertion = $dstMetadata->getBoolean('assertion.encryption', false);
@@ -383,7 +398,7 @@ class Message
         try {
             $keys = self::getDecryptionKeys($srcMetadata, $dstMetadata);
         } catch (\Exception $e) {
-            throw new \SimpleSAML\Error\Exception('Error decrypting assertion: '.$e->getMessage());
+            throw new SSP_Error\Exception('Error decrypting assertion: '.$e->getMessage());
         }
 
         $blacklist = self::getBlacklistedAlgorithms($srcMetadata, $dstMetadata);
@@ -392,10 +407,10 @@ class Message
         foreach ($keys as $i => $key) {
             try {
                 $ret = $assertion->getAssertion($key, $blacklist);
-                \SimpleSAML\Logger::debug('Decryption with key #'.$i.' succeeded.');
+                Logger::debug('Decryption with key #'.$i.' succeeded.');
                 return $ret;
             } catch (\Exception $e) {
-                \SimpleSAML\Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
+                Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
                 $lastException = $e;
             }
         }
@@ -417,9 +432,9 @@ class Message
      * @throws \SimpleSAML\Error\Exception if we cannot get the decryption keys or decryption fails.
      */
     private static function decryptAttributes(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata,
-        \SAML2\Assertion &$assertion
+        Configuration $srcMetadata,
+        Configuration $dstMetadata,
+        Assertion &$assertion
     ) {
         if (!$assertion->hasEncryptedAttributes()) {
             return;
@@ -428,7 +443,7 @@ class Message
         try {
             $keys = self::getDecryptionKeys($srcMetadata, $dstMetadata);
         } catch (\Exception $e) {
-            throw new \SimpleSAML\Error\Exception('Error decrypting attributes: '.$e->getMessage());
+            throw new SSP_Error\Exception('Error decrypting attributes: '.$e->getMessage());
         }
 
         $blacklist = self::getBlacklistedAlgorithms($srcMetadata, $dstMetadata);
@@ -437,15 +452,15 @@ class Message
         foreach ($keys as $i => $key) {
             try {
                 $assertion->decryptAttributes($key, $blacklist);
-                \SimpleSAML\Logger::debug('Attribute decryption with key #'.$i.' succeeded.');
+                Logger::debug('Attribute decryption with key #'.$i.' succeeded.');
                 $error = false;
                 break;
             } catch (\Exception $e) {
-                \SimpleSAML\Logger::debug('Attribute decryption failed with exception: '.$e->getMessage());
+                Logger::debug('Attribute decryption failed with exception: '.$e->getMessage());
             }
         }
         if ($error) {
-            throw new \SimpleSAML\Error\Exception('Could not decrypt the attributes');
+            throw new SSP_Error\Exception('Could not decrypt the attributes');
         }
     }
 
@@ -457,7 +472,7 @@ class Message
      *
      * @return \SimpleSAML\Module\saml\Error The error.
      */
-    public static function getResponseError(\SAML2\StatusResponse $response)
+    public static function getResponseError(StatusResponse $response)
     {
         $status = $response->getStatus();
         return new \SimpleSAML\Module\saml\Error($status['Code'], $status['SubCode'], $status['Message']);
@@ -472,10 +487,10 @@ class Message
      * @return \SAML2\AuthnRequest An authentication request object.
      */
     public static function buildAuthnRequest(
-        \SimpleSAML\Configuration $spMetadata,
-        \SimpleSAML\Configuration $idpMetadata
+        Configuration $spMetadata,
+        Configuration $idpMetadata
     ) {
-        $ar = new \SAML2\AuthnRequest();
+        $ar = new AuthnRequest();
 
         // get the NameIDPolicy to apply. IdP metadata has precedence.
         $nameIdPolicy = null;
@@ -485,7 +500,7 @@ class Message
             $nameIdPolicy = $spMetadata->getValue('NameIDPolicy');
         }
 
-        $policy = \SimpleSAML\Utils\Config\Metadata::parseNameIdPolicy($nameIdPolicy);
+        $policy = Utils\Config\Metadata::parseNameIdPolicy($nameIdPolicy);
         if ($policy !== null) {
             // either we have a policy set, or we used the transient default
             $ar->setNameIdPolicy($policy);
@@ -495,15 +510,15 @@ class Message
         $ar->setIsPassive($spMetadata->getBoolean('IsPassive', false));
 
         $protbind = $spMetadata->getValueValidate('ProtocolBinding', [
-            \SAML2\Constants::BINDING_HTTP_POST,
-            \SAML2\Constants::BINDING_HOK_SSO,
-            \SAML2\Constants::BINDING_HTTP_ARTIFACT,
-            \SAML2\Constants::BINDING_HTTP_REDIRECT,
-        ], \SAML2\Constants::BINDING_HTTP_POST);
+            Constants::BINDING_HTTP_POST,
+            Constants::BINDING_HOK_SSO,
+            Constants::BINDING_HTTP_ARTIFACT,
+            Constants::BINDING_HTTP_REDIRECT,
+        ], Constants::BINDING_HTTP_POST);
 
         // Shoaib: setting the appropriate binding based on parameter in sp-metadata defaults to HTTP_POST
         $ar->setProtocolBinding($protbind);
-        $issuer = new \SAML2\XML\saml\Issuer();
+        $issuer = new Issuer();
         $issuer->setValue($spMetadata->getString('entityid'));
         $ar->setIssuer($issuer);
         $ar->setAssertionConsumerServiceIndex($spMetadata->getInteger('AssertionConsumerServiceIndex', null));
@@ -512,11 +527,11 @@ class Message
         if ($spMetadata->hasValue('AuthnContextClassRef')) {
             $accr = $spMetadata->getArrayizeString('AuthnContextClassRef');
             $comp = $spMetadata->getValueValidate('AuthnContextComparison', [
-                \SAML2\Constants::COMPARISON_EXACT,
-                \SAML2\Constants::COMPARISON_MINIMUM,
-                \SAML2\Constants::COMPARISON_MAXIMUM,
-                \SAML2\Constants::COMPARISON_BETTER,
-            ], \SAML2\Constants::COMPARISON_EXACT);
+                Constants::COMPARISON_EXACT,
+                Constants::COMPARISON_MINIMUM,
+                Constants::COMPARISON_MAXIMUM,
+                Constants::COMPARISON_BETTER,
+            ], Constants::COMPARISON_EXACT);
             $ar->setRequestedAuthnContext(['AuthnContextClassRef' => $accr, 'Comparison' => $comp]);
         }
 
@@ -534,10 +549,10 @@ class Message
      * @return \SAML2\LogoutRequest A logout request object.
      */
     public static function buildLogoutRequest(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata
+        Configuration $srcMetadata,
+        Configuration $dstMetadata
     ) {
-        $lr = new \SAML2\LogoutRequest();
+        $lr = new LogoutRequest();
         $issuer = new Issuer();
         $issuer->setValue($srcMetadata->getString('entityid'));
         $issuer->setFormat(Constants::NAMEID_ENTITY);
@@ -557,10 +572,10 @@ class Message
      * @return \SAML2\LogoutResponse A logout response object.
      */
     public static function buildLogoutResponse(
-        \SimpleSAML\Configuration $srcMetadata,
-        \SimpleSAML\Configuration $dstMetadata
+        Configuration $srcMetadata,
+        Configuration $dstMetadata
     ) {
-        $lr = new \SAML2\LogoutResponse();
+        $lr = new LogoutResponse();
         $issuer = new Issuer();
         $issuer->setValue($srcMetadata->getString('entityid'));
         $issuer->setFormat(Constants::NAMEID_ENTITY);
@@ -587,16 +602,16 @@ class Message
      * @throws \Exception if the destination of the response does not match the current URL.
      */
     public static function processResponse(
-        \SimpleSAML\Configuration $spMetadata,
-        \SimpleSAML\Configuration $idpMetadata,
-        \SAML2\Response $response
+        Configuration $spMetadata,
+        Configuration $idpMetadata,
+        Response $response
     ) {
         if (!$response->isSuccess()) {
             throw self::getResponseError($response);
         }
 
         // validate Response-element destination
-        $currentURL = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
+        $currentURL = Utils\HTTP::getSelfURLNoQuery();
         $msgDestination = $response->getDestination();
         if ($msgDestination !== null && $msgDestination !== $currentURL) {
             throw new \Exception('Destination in response doesn\'t match the current URL. Destination is "'.
@@ -611,7 +626,7 @@ class Message
          */
         $assertion = $response->getAssertions();
         if (empty($assertion)) {
-            throw new \SimpleSAML\Error\Exception('No assertions found in response from IdP.');
+            throw new SSP_Error\Exception('No assertions found in response from IdP.');
         }
 
         $ret = [];
@@ -640,13 +655,13 @@ class Message
      * @throws \Exception if we couldn't decrypt the NameID for unexpected reasons.
      */
     private static function processAssertion(
-        \SimpleSAML\Configuration $spMetadata,
-        \SimpleSAML\Configuration $idpMetadata,
-        \SAML2\Response $response,
+        Configuration $spMetadata,
+        Configuration $idpMetadata,
+        Response $response,
         $assertion,
         $responseSigned
     ) {
-        assert($assertion instanceof \SAML2\Assertion || $assertion instanceof \SAML2\EncryptedAssertion);
+        assert($assertion instanceof Assertion || $assertion instanceof EncryptedAssertion);
         assert(is_bool($responseSigned));
 
         $assertion = self::decryptAssertion($idpMetadata, $spMetadata, $assertion);
@@ -654,14 +669,14 @@ class Message
 
         if (!self::checkSign($idpMetadata, $assertion)) {
             if (!$responseSigned) {
-                throw new \SimpleSAML\Error\Exception('Neither the assertion nor the response was signed.');
+                throw new SSP_Error\Exception('Neither the assertion nor the response was signed.');
             }
         } // at least one valid signature found
 
-        $currentURL = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
+        $currentURL = Utils\HTTP::getSelfURLNoQuery();
 
         // check various properties of the assertion
-        $config = \SimpleSAML\Configuration::getInstance();
+        $config = Configuration::getInstance();
         $allowed_clock_skew = $config->getInteger('assertion.allowed_clock_skew', 180);
         $options = [
             'options' => [
@@ -673,19 +688,19 @@ class Message
         $allowed_clock_skew = filter_var($allowed_clock_skew, FILTER_VALIDATE_INT, $options);
         $notBefore = $assertion->getNotBefore();
         if ($notBefore !== null && $notBefore > time() + $allowed_clock_skew) {
-            throw new \SimpleSAML\Error\Exception(
+            throw new SSP_Error\Exception(
                 'Received an assertion that is valid in the future. Check clock synchronization on IdP and SP.'
             );
         }
         $notOnOrAfter = $assertion->getNotOnOrAfter();
         if ($notOnOrAfter !== null && $notOnOrAfter <= time() - $allowed_clock_skew) {
-            throw new \SimpleSAML\Error\Exception(
+            throw new SSP_Error\Exception(
                 'Received an assertion that has expired. Check clock synchronization on IdP and SP.'
             );
         }
         $sessionNotOnOrAfter = $assertion->getSessionNotOnOrAfter();
         if ($sessionNotOnOrAfter !== null && $sessionNotOnOrAfter <= time() - $allowed_clock_skew) {
-            throw new \SimpleSAML\Error\Exception(
+            throw new SSP_Error\Exception(
                 'Received an assertion with a session that has expired. Check clock synchronization on IdP and SP.'
             );
         }
@@ -694,14 +709,14 @@ class Message
             $spEntityId = $spMetadata->getString('entityid');
             if (!in_array($spEntityId, $validAudiences, true)) {
                 $candidates = '['.implode('], [', $validAudiences).']';
-                throw new \SimpleSAML\Error\Exception('This SP ['.$spEntityId.
+                throw new SSP_Error\Exception('This SP ['.$spEntityId.
                     ']  is not a valid audience for the assertion. Candidates were: '.$candidates);
             }
         }
 
         $found = false;
         $lastError = 'No SubjectConfirmation element in Subject.';
-        $validSCMethods = [\SAML2\Constants::CM_BEARER, \SAML2\Constants::CM_HOK, \SAML2\Constants::CM_VOUCHES];
+        $validSCMethods = [Constants::CM_BEARER, Constants::CM_HOK, Constants::CM_VOUCHES];
         foreach ($assertion->getSubjectConfirmation() as $sc) {
             $method = $sc->getMethod();
             if (!in_array($method, $validSCMethods, true)) {
@@ -714,20 +729,20 @@ class Message
             if ($hok === null) {
                 $hok = $spMetadata->getBoolean('saml20.hok.assertion', false);
             }
-            if ($method === \SAML2\Constants::CM_BEARER && $hok) {
+            if ($method === Constants::CM_BEARER && $hok) {
                 $lastError = 'Bearer SubjectConfirmation received, but Holder-of-Key SubjectConfirmation needed';
                 continue;
             }
-            if ($method === \SAML2\Constants::CM_HOK && !$hok) {
+            if ($method === Constants::CM_HOK && !$hok) {
                 $lastError = 'Holder-of-Key SubjectConfirmation received, '.
                     'but the Holder-of-Key profile is not enabled.';
                 continue;
             }
 
             $scd = $sc->getSubjectConfirmationData();
-            if ($method === \SAML2\Constants::CM_HOK) {
+            if ($method === Constants::CM_HOK) {
                 // check HoK Assertion
-                if (\SimpleSAML\Utils\HTTP::isHTTPS() === false) {
+                if (Utils\HTTP::isHTTPS() === false) {
                     $lastError = 'No HTTPS connection, but required for Holder-of-Key SSO';
                     continue;
                 }
@@ -748,7 +763,7 @@ class Message
 
                 $keyInfo = [];
                 foreach ($scd->info as $thing) {
-                    if ($thing instanceof \SAML2\XML\ds\KeyInfo) {
+                    if ($thing instanceof KeyInfo) {
                         $keyInfo[] = $thing;
                     }
                 }
@@ -760,7 +775,7 @@ class Message
 
                 $x509data = [];
                 foreach ($keyInfo[0]->info as $thing) {
-                    if ($thing instanceof \SAML2\XML\ds\X509Data) {
+                    if ($thing instanceof X509Data) {
                         $x509data[] = $thing;
                     }
                 }
@@ -772,7 +787,7 @@ class Message
 
                 $x509cert = [];
                 foreach ($x509data[0]->data as $thing) {
-                    if ($thing instanceof \SAML2\XML\ds\X509Certificate) {
+                    if ($thing instanceof X509Certificate) {
                         $x509cert[] = $thing;
                     }
                 }
@@ -825,7 +840,7 @@ class Message
             break;
         }
         if (!$found) {
-            throw new \SimpleSAML\Error\Exception('Error validating SubjectConfirmation in Assertion: '.$lastError);
+            throw new SSP_Error\Exception('Error validating SubjectConfirmation in Assertion: '.$lastError);
         } // as far as we can tell, the assertion is valid
 
         // maybe we need to base64 decode the attributes in the assertion?
@@ -848,7 +863,7 @@ class Message
             try {
                 $keys = self::getDecryptionKeys($idpMetadata, $spMetadata);
             } catch (\Exception $e) {
-                throw new \SimpleSAML\Error\Exception('Error decrypting NameID: '.$e->getMessage());
+                throw new SSP_Error\Exception('Error decrypting NameID: '.$e->getMessage());
             }
 
             $blacklist = self::getBlacklistedAlgorithms($idpMetadata, $spMetadata);
@@ -857,11 +872,11 @@ class Message
             foreach ($keys as $i => $key) {
                 try {
                     $assertion->decryptNameId($key, $blacklist);
-                    \SimpleSAML\Logger::debug('Decryption with key #'.$i.' succeeded.');
+                    Logger::debug('Decryption with key #'.$i.' succeeded.');
                     $lastException = null;
                     break;
                 } catch (\Exception $e) {
-                    \SimpleSAML\Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
+                    Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
                     $lastException = $e;
                 }
             }
@@ -883,7 +898,7 @@ class Message
      *
      * @throws \SimpleSAML\Error\Exception if there is no supported encryption key in the metadata of this entity.
      */
-    public static function getEncryptionKey(\SimpleSAML\Configuration $metadata)
+    public static function getEncryptionKey(Configuration $metadata)
     {
 
         $sharedKey = $metadata->getString('sharedkey', null);
@@ -906,7 +921,7 @@ class Message
             }
         }
 
-        throw new \SimpleSAML\Error\Exception('No supported encryption key in '.
+        throw new SSP_Error\Exception('No supported encryption key in '.
             var_export($metadata->getString('entityid'), true));
     }
 }
diff --git a/modules/saml/lib/SP/LogoutStore.php b/modules/saml/lib/SP/LogoutStore.php
index 234380fa3224a7f4d019fdd15fe2333db981bb32..94c06782ec3745f98c99e722ef868bb4fcb8844c 100644
--- a/modules/saml/lib/SP/LogoutStore.php
+++ b/modules/saml/lib/SP/LogoutStore.php
@@ -2,6 +2,13 @@
 
 namespace SimpleSAML\Module\saml\SP;
 
+use PDO;
+use SAML2\XML\saml\NameID;
+use SimpleSAML\Logger;
+use SimpleSAML\Session;
+use SimpleSAML\Store;
+use SimpleSAML\Utils;
+
 /**
  * A directory over logout information.
  *
@@ -16,7 +23,7 @@ class LogoutStore
      * @param \SimpleSAML\Store\SQL $store  The datastore.
      * @return void
      */
-    private static function createLogoutTable(\SimpleSAML\Store\SQL $store)
+    private static function createLogoutTable(Store\SQL $store)
     {
         $tableVer = $store->getTableVersion('saml_LogoutStore');
         if ($tableVer === 2) {
@@ -38,7 +45,7 @@ class LogoutStore
             try {
                 $store->pdo->exec($query);
             } catch (\Exception $e) {
-                \SimpleSAML\Logger::warning('Database error: '.var_export($store->pdo->errorInfo(), true));
+                Logger::warning('Database error: '.var_export($store->pdo->errorInfo(), true));
                 return;
             }
             $store->setTableVersion('saml_LogoutStore', 2);
@@ -73,9 +80,9 @@ class LogoutStore
      * @param \SimpleSAML\Store\SQL $store  The datastore.
      * @return void
      */
-    private static function cleanLogoutStore(\SimpleSAML\Store\SQL $store)
+    private static function cleanLogoutStore(Store\SQL $store)
     {
-        \SimpleSAML\Logger::debug('saml.LogoutStore: Cleaning logout store.');
+        Logger::debug('saml.LogoutStore: Cleaning logout store.');
 
         $query = 'DELETE FROM '.$store->prefix.'_saml_LogoutStore WHERE _expire < :now';
         $params = ['now' => gmdate('Y-m-d H:i:s')];
@@ -97,7 +104,7 @@ class LogoutStore
      * @return void
      */
     private static function addSessionSQL(
-        \SimpleSAML\Store\SQL $store,
+        Store\SQL $store,
         $authId,
         $nameId,
         $sessionIndex,
@@ -139,7 +146,7 @@ class LogoutStore
      * @param string $nameId  The hash of the users NameID.
      * @return array  Associative array of SessionIndex =>  SessionId.
      */
-    private static function getSessionsSQL(\SimpleSAML\Store\SQL $store, $authId, $nameId)
+    private static function getSessionsSQL(Store\SQL $store, $authId, $nameId)
     {
         assert(is_string($authId));
         assert(is_string($nameId));
@@ -159,7 +166,7 @@ class LogoutStore
         $query->execute($params);
 
         $res = [];
-        while (($row = $query->fetch(\PDO::FETCH_ASSOC)) !== false) {
+        while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== false) {
             $res[$row['_sessionindex']] = $row['_sessionid'];
         }
 
@@ -176,7 +183,7 @@ class LogoutStore
      * @param array $sessionIndexes  The session indexes.
      * @return array  Associative array of SessionIndex =>  SessionId.
      */
-    private static function getSessionsStore(\SimpleSAML\Store $store, $authId, $nameId, array $sessionIndexes)
+    private static function getSessionsStore(Store $store, $authId, $nameId, array $sessionIndexes)
     {
         assert(is_string($authId));
         assert(is_string($nameId));
@@ -222,10 +229,10 @@ class LogoutStore
              * it supports SLO, but we don't want an LogoutRequest with a specific
              * SessionIndex to match this session. We therefore generate our own session index.
              */
-            $sessionIndex = \SimpleSAML\Utils\Random::generateID();
+            $sessionIndex = Utils\Random::generateID();
         }
 
-        $store = \SimpleSAML\Store::getInstance();
+        $store = Store::getInstance();
         if ($store === false) {
             // We don't have a datastore.
             return;
@@ -234,7 +241,7 @@ class LogoutStore
         // serialize and anonymize the NameID
         // TODO: remove this conditional statement
         if (is_array($nameId)) {
-            $nameId = \SAML2\XML\saml\NameID::fromArray($nameId);
+            $nameId = NameID::fromArray($nameId);
         }
         $strNameId = serialize($nameId);
         $strNameId = sha1($strNameId);
@@ -244,10 +251,10 @@ class LogoutStore
             $sessionIndex = sha1($sessionIndex);
         }
 
-        $session = \SimpleSAML\Session::getSessionFromRequest();
+        $session = Session::getSessionFromRequest();
         $sessionId = $session->getSessionId();
 
-        if ($store instanceof \SimpleSAML\Store\SQL) {
+        if ($store instanceof Store\SQL) {
             self::addSessionSQL($store, $authId, $strNameId, $sessionIndex, $expire, $sessionId);
         } else {
             $store->set('saml.LogoutStore', $strNameId.':'.$sessionIndex, $sessionId, $expire);
@@ -267,7 +274,7 @@ class LogoutStore
     {
         assert(is_string($authId));
 
-        $store = \SimpleSAML\Store::getInstance();
+        $store = Store::getInstance();
         if ($store === false) {
             // We don't have a datastore
             return false;
@@ -276,7 +283,7 @@ class LogoutStore
         // serialize and anonymize the NameID
         // TODO: remove this conditional statement
         if (is_array($nameId)) {
-            $nameId = \SAML2\XML\saml\NameID::fromArray($nameId);
+            $nameId = NameID::fromArray($nameId);
         }
         $strNameId = serialize($nameId);
         $strNameId = sha1($strNameId);
@@ -292,7 +299,7 @@ class LogoutStore
         // Remove reference
         unset($sessionIndex);
 
-        if ($store instanceof \SimpleSAML\Store\SQL) {
+        if ($store instanceof Store\SQL) {
             $sessions = self::getSessionsSQL($store, $authId, $strNameId);
         } elseif (empty($sessionIndexes)) {
             // We cannot fetch all sessions without a SQL store
@@ -309,26 +316,26 @@ class LogoutStore
         $numLoggedOut = 0;
         foreach ($sessionIndexes as $sessionIndex) {
             if (!isset($sessions[$sessionIndex])) {
-                \SimpleSAML\Logger::info('saml.LogoutStore: Logout requested for unknown SessionIndex.');
+                Logger::info('saml.LogoutStore: Logout requested for unknown SessionIndex.');
                 continue;
             }
 
             $sessionId = $sessions[$sessionIndex];
 
-            $session = \SimpleSAML\Session::getSession($sessionId);
+            $session = Session::getSession($sessionId);
             if ($session === null) {
-                \SimpleSAML\Logger::info('saml.LogoutStore: Skipping logout of missing session.');
+                Logger::info('saml.LogoutStore: Skipping logout of missing session.');
                 continue;
             }
 
             if (!$session->isValid($authId)) {
-                \SimpleSAML\Logger::info(
+                Logger::info(
                     'saml.LogoutStore: Skipping logout of session because it isn\'t authenticated.'
                 );
                 continue;
             }
 
-            \SimpleSAML\Logger::info(
+            Logger::info(
                 'saml.LogoutStore: Logging out of session with trackId ['.$session->getTrackID().'].'
             );
             $session->doLogout($authId);