public function authenticate($redirectUrl, $hostedDomain, $legacyRealm = NULL)
 {
     $jwt = HttpUtil::getJWTFromHeader();
     $jwtPayload = self::getValidatedJWTPayload($jwt);
     if ($jwtPayload == NULL) {
         $requestError = filter_input(INPUT_GET, 'error');
         if (isset($requestError)) {
             self::logErrorAndClearCache($requestError);
             HttpUtil::replyError(500, $requestError);
         }
         $requestState = filter_input(INPUT_GET, 'state');
         $requestCode = filter_input(INPUT_GET, 'code');
         if (!isset($requestState)) {
             $this->requestAuthCode($redirectUrl, $hostedDomain, $legacyRealm);
         } else {
             if ($requestState != $this->getAntiForgeryStateToken(FALSE)) {
                 self::logErrorAndClearCache("Invalid state parameter: expected '" . $this->getAntiForgeryStateToken(FALSE) . "' but got '{$requestState}'.\n{$_SERVER['REQUEST_URI']}");
                 HttpUtil::replyError(401, 'Invalid state parameter');
             } else {
                 if (isset($requestCode)) {
                     $jwt = $this->exchangeCodeForJWT($requestCode, $redirectUrl);
                     // Temporarilly store the JWT in the session.
                     SessionCache::set(self::$PARKED_JWT_CACHE_KEY, $jwt);
                 }
             }
         }
     }
 }