loadState() public static method

This function retrieves saved state information. If the state information has been lost, it will attempt to restart the request by calling the restart URL which is embedded in the state information. If there is no restart information available, an exception will be thrown.
public static loadState ( string $id, string $stage, boolean $allowMissing = false ) : array | null
$id string State identifier (with embedded restart information).
$stage string The stage the state should have been saved in.
$allowMissing boolean Whether to allow the state to be missing.
return array | null State information, or null if the state is missing and $allowMissing is true.
Exemplo n.º 1
0
 public static function handleLogin($authStateId, $xmlToken)
 {
     assert('is_string($authStateId)');
     $config = SimpleSAML_Configuration::getInstance();
     $autoconfig = $config->copyFromBase('logininfocard', 'config-login-infocard.php');
     $idp_key = $autoconfig->getValue('idp_key');
     $idp_pass = $autoconfig->getValue('idp_key_pass', NULL);
     $sts_crt = $autoconfig->getValue('sts_crt');
     $Infocard = $autoconfig->getValue('InfoCard');
     $infocard = new sspmod_InfoCard_RP_InfoCard();
     $infocard->addIDPKey($idp_key, $idp_pass);
     $infocard->addSTSCertificate($sts_crt);
     if (!$xmlToken) {
         SimpleSAML_Logger::debug("XMLtoken: " . $xmlToken);
     } else {
         SimpleSAML_Logger::debug("NOXMLtoken: " . $xmlToken);
     }
     $claims = $infocard->process($xmlToken);
     if ($claims->isValid()) {
         $attributes = array();
         foreach ($Infocard['requiredClaims'] as $claim => $data) {
             $attributes[$claim] = array($claims->{$claim});
         }
         foreach ($Infocard['optionalClaims'] as $claim => $data) {
             $attributes[$claim] = array($claims->{$claim});
         }
         // sanitize the input
         $sid = SimpleSAML_Utilities::parseStateID($authStateId);
         if (!is_null($sid['url'])) {
             SimpleSAML_Utilities::checkURLAllowed($sid['url']);
         }
         /* Retrieve the authentication state. */
         $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID);
         /* Find authentication source. */
         assert('array_key_exists(self::AUTHID, $state)');
         $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]);
         if ($source === NULL) {
             throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
         }
         $state['Attributes'] = $attributes;
         unset($infocard);
         unset($claims);
         SimpleSAML_Auth_Source::completeAuth($state);
     } else {
         unset($infocard);
         unset($claims);
         return 'wrong_IC';
     }
 }
Exemplo n.º 2
0
/**
 * Check the credentials that the user got from the A-Select server.
 * This function is called after the user returns from the A-Select server.
 *
 * @author Wessel Dankers, Tilburg University
 */
function check_credentials()
{
    if (!array_key_exists('ssp_state', $_REQUEST)) {
        SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing ssp_state parameter"));
    }
    $id = $_REQUEST['ssp_state'];
    // sanitize the input
    $sid = SimpleSAML_Utilities::parseStateID($id);
    if (!is_null($sid['url'])) {
        SimpleSAML_Utilities::checkURLAllowed($sid['url']);
    }
    $state = SimpleSAML_Auth_State::loadState($id, 'aselect:login');
    if (!array_key_exists('a-select-server', $_REQUEST)) {
        SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing a-select-server parameter"));
    }
    $server_id = $_REQUEST['a-select-server'];
    if (!array_key_exists('aselect_credentials', $_REQUEST)) {
        SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing aselect_credentials parameter"));
    }
    $credentials = $_REQUEST['aselect_credentials'];
    if (!array_key_exists('rid', $_REQUEST)) {
        SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Missing rid parameter"));
    }
    $rid = $_REQUEST['rid'];
    try {
        if (!array_key_exists('aselect::authid', $state)) {
            throw new SimpleSAML_Error_Exception("ASelect authentication source missing in state");
        }
        $authid = $state['aselect::authid'];
        $aselect = SimpleSAML_Auth_Source::getById($authid);
        if (is_null($aselect)) {
            throw new SimpleSAML_Error_Exception("Could not find authentication source with id {$authid}");
        }
        $creds = $aselect->verify_credentials($server_id, $credentials, $rid);
        if (array_key_exists('attributes', $creds)) {
            $state['Attributes'] = $creds['attributes'];
        } else {
            $res = $creds['res'];
            $state['Attributes'] = array('uid' => array($res['uid']), 'organization' => array($res['organization']));
        }
    } catch (Exception $e) {
        SimpleSAML_Auth_State::throwException($state, $e);
    }
    SimpleSAML_Auth_Source::completeAuth($state);
    SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_Exception("Internal error in A-Select component"));
}
 /**
  * Continue the logout operation.
  *
  * This function will never return.
  *
  * @param string $assocId The association that is terminated.
  * @param string|null $relayState The RelayState from the start of the logout.
  * @param SimpleSAML_Error_Exception|null $error The error that occurred during session termination (if any).
  *
  * @throws SimpleSAML_Error_Exception If the RelayState was lost during logout.
  */
 public function onResponse($assocId, $relayState, SimpleSAML_Error_Exception $error = null)
 {
     assert('is_string($assocId)');
     assert('is_string($relayState) || is_null($relayState)');
     if ($relayState === null) {
         throw new SimpleSAML_Error_Exception('RelayState lost during logout.');
     }
     $state = SimpleSAML_Auth_State::loadState($relayState, 'core:LogoutTraditional');
     if ($error === null) {
         SimpleSAML_Logger::info('Logged out of ' . var_export($assocId, true) . '.');
         $this->idp->terminateAssociation($assocId);
     } else {
         SimpleSAML_Logger::warning('Error received from ' . var_export($assocId, true) . ' during logout:');
         $error->logWarning();
         $state['core:Failed'] = true;
     }
     self::logoutNextSP($state);
 }
Exemplo n.º 4
0
 /**
  * Continue the logout operation.
  *
  * This function will never return.
  *
  * @param string $assocId  The association that is terminated.
  * @param string|NULL $relayState  The RelayState from the start of the logout.
  * @param SimpleSAML_Error_Exception|NULL $error  The error that occurred during session termination (if any).
  */
 public function onResponse($assocId, $relayState, SimpleSAML_Error_Exception $error = NULL)
 {
     assert('is_string($assocId)');
     assert('is_string($relayState) || is_null($relayState)');
     if ($relayState === NULL) {
         throw new SimpleSAML_Error_Exception('RelayState lost during logout.');
     }
     // sanitize the input
     $sid = SimpleSAML_Utilities::parseStateID($relayState);
     if (!is_null($sid['url'])) {
         SimpleSAML_Utilities::checkURLAllowed($sid['url']);
     }
     $state = SimpleSAML_Auth_State::loadState($relayState, 'core:LogoutTraditional');
     if ($error === NULL) {
         SimpleSAML_Logger::info('Logged out of ' . var_export($assocId, TRUE) . '.');
         $this->idp->terminateAssociation($assocId);
     } else {
         SimpleSAML_Logger::warning('Error received from ' . var_export($assocId, TRUE) . ' during logout:');
         $error->logWarning();
         $state['core:Failed'] = TRUE;
     }
     self::logoutNextSP($state);
 }
 public static function resume()
 {
     if (!isset($_REQUEST['State'])) {
         throw new SimpleSAML_Error_BadRequest('Missing "State" parameter.');
     }
     $state = SimpleSAML_Auth_State::loadState($_REQUEST['State'], 'negotiateserver:Negotiate');
     $source = SimpleSAML_Auth_Source::getById($state['negotiateserver:AuthID']);
     if ($source === NULL) {
         throw new SimpleSAML_Error_Exception('Could not find authentication source with id ' . $state[self::authId]);
     }
     if (!$source instanceof self) {
         throw new SimpleSAML_Error_Exception('Authentication source type changed.');
     }
     if (empty($state['UserIdentifier'])) {
         throw new SimpleSAML_Error_Exception('User identifier is empty or not set.');
     }
     $attributes = $source->getUserAttributes($state['UserIdentifier']);
     if ($attributes === NULL) {
         throw new SimpleSAML_Error_Exception('User not authenticated after login page.');
     }
     $state['Attributes'] = $attributes;
     SimpleSAML_Auth_Source::completeAuth($state);
     assert('FALSE');
 }
Exemplo n.º 6
0
<?php

/**
 * Show a warning to an user about the SP requesting SSO a short time after
 * doing it previously.
 *
 * @package SimpleSAMLphp
 */
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($id, 'core:short_sso_interval');
$session = SimpleSAML_Session::getSessionFromRequest();
if (array_key_exists('continue', $_REQUEST)) {
    // The user has pressed the continue/retry-button
    SimpleSAML_Auth_ProcessingChain::resumeProcessing($state);
}
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'core:short_sso_interval.php');
$t->data['target'] = SimpleSAML\Module::getModuleURL('core/short_sso_interval.php');
$t->data['params'] = array('StateId' => $id);
$t->data['trackId'] = $session->getTrackID();
$t->show();
Exemplo n.º 7
0
<?php

/**
 * Handle linkback() response from CAS.
 */
if (!isset($_GET['stateID'])) {
    throw new SimpleSAML_Error_BadRequest('Missing stateID parameter.');
}
$stateId = (string) $_GET['stateID'];
if (!isset($_GET['ticket'])) {
    throw new SimpleSAML_Error_BadRequest('Missing ticket parameter.');
}
// sanitize the input
$sid = SimpleSAML_Utilities::parseStateID($stateId);
if (!is_null($sid['url'])) {
    SimpleSAML_Utilities::checkURLAllowed($sid['url']);
}
$state = SimpleSAML_Auth_State::loadState($stateId, sspmod_cas_Auth_Source_CAS::STAGE_INIT);
$state['cas:ticket'] = (string) $_GET['ticket'];
/* Find authentication source. */
assert('array_key_exists(sspmod_cas_Auth_Source_CAS::AUTHID, $state)');
$sourceId = $state[sspmod_cas_Auth_Source_CAS::AUTHID];
$source = SimpleSAML_Auth_Source::getById($sourceId);
if ($source === NULL) {
    throw new Exception('Could not find authentication source with id ' . $sourceId);
}
$source->finalStep($state);
Exemplo n.º 8
0
<?php

/**
 * about2expire.php
 *
 * @package simpleSAMLphp
 */
SimpleSAML_Logger::info('expirycheck - User has been warned that NetID is near to expirational date.');
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
// sanitize the input
$sid = SimpleSAML_Utilities::parseStateID($id);
if (!is_null($sid['url'])) {
    SimpleSAML_Utilities::checkURLAllowed($sid['url']);
}
$state = SimpleSAML_Auth_State::loadState($id, 'expirywarning:about2expire');
if (array_key_exists('yes', $_REQUEST)) {
    /* The user has pressed the yes-button. */
    SimpleSAML_Auth_ProcessingChain::resumeProcessing($state);
}
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'expirycheck:about2expire.php');
$t->data['yesTarget'] = SimpleSAML_Module::getModuleURL('expirycheck/about2expire.php');
$t->data['yesData'] = array('StateId' => $id);
$t->data['daysleft'] = $state['daysleft'];
$t->data['expireOnDate'] = $state['expireOnDate'];
$t->data['netId'] = $state['netId'];
$t->show();
/**
 * This page shows a username/password/organization login form, and passes information from
 * itto the sspmod_core_Auth_UserPassBase class, which is a generic class for
 * username/password/organization authentication.
 *
 * @author Olav Morken, UNINETT AS.
 * @package simpleSAMLphp
 * @version $Id$
 */
if (!array_key_exists('AuthState', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing AuthState parameter.');
}
$authStateId = $_REQUEST['AuthState'];
/* Retrieve the authentication state. */
$state = SimpleSAML_Auth_State::loadState($authStateId, sspmod_core_Auth_UserPassOrgBase::STAGEID);
$source = SimpleSAML_Auth_Source::getById($state[sspmod_core_Auth_UserPassOrgBase::AUTHID]);
if ($source === NULL) {
    throw new Exception('Could not find authentication source with id ' . $state[sspmod_core_Auth_UserPassOrgBase::AUTHID]);
}
$organizations = sspmod_core_Auth_UserPassOrgBase::listOrganizations($authStateId);
if (array_key_exists('username', $_REQUEST)) {
    $username = $_REQUEST['username'];
} elseif ($source->getRememberUsernameEnabled() && array_key_exists($source->getAuthId() . '-username', $_COOKIE)) {
    $username = $_COOKIE[$source->getAuthId() . '-username'];
} elseif (isset($state['core:username'])) {
    $username = (string) $state['core:username'];
} else {
    $username = '';
}
if (array_key_exists('password', $_REQUEST)) {
Exemplo n.º 10
0
    die('Missing ReturnTo parameter.');
}
$returnTo = \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']);
/*
 * The following piece of code would never be found in a real authentication page. Its
 * purpose in this example is to make this example safer in the case where the
 * administrator of * the IdP leaves the exampleauth-module enabled in a production
 * environment.
 *
 * What we do here is to extract the $state-array identifier, and check that it belongs to
 * the exampleauth:External process.
 */
if (!preg_match('@State=(.*)@', $returnTo, $matches)) {
    die('Invalid ReturnTo URL for this example.');
}
SimpleSAML_Auth_State::loadState(urldecode($matches[1]), 'exampleauth:External');
/*
 * The loadState-function will not return if the second parameter does not
 * match the parameter passed to saveState, so by now we know that we arrived here
 * through the exampleauth:External authentication page.
 */
/*
 * Our list of users.
 */
$users = array('student' => array('password' => 'student', 'uid' => 'student', 'name' => 'Student Name', 'mail' => '*****@*****.**', 'type' => 'student'), 'admin' => array('password' => 'admin', 'uid' => 'admin', 'name' => 'Admin Name', 'mail' => '*****@*****.**', 'type' => 'employee'));
/*
 * Time to handle login responses.
 * Since this is a dummy example, we accept any data.
 */
$badUserPass = FALSE;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
Exemplo n.º 11
0
<?php

/**
 * This script warns a user that his/her certificate is about to expire.
 *
 * @package SimpleSAMLphp
 */
SimpleSAML\Logger::info('AuthX509 - Showing expiry warning to user');
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($id, 'warning:expire');
if (array_key_exists('proceed', $_REQUEST)) {
    // The user has pressed the proceed-button
    SimpleSAML_Auth_ProcessingChain::resumeProcessing($state);
}
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'authX509:X509warning.php');
$t->data['target'] = SimpleSAML\Module::getModuleURL('authX509/expirywarning.php');
$t->data['data'] = array('StateId' => $id);
$t->data['daysleft'] = $state['daysleft'];
$t->data['renewurl'] = $state['renewurl'];
$t->data['errorcodes'] = SimpleSAML\Error\Errorcodes::getAllErrorCodeMessages();
$t->show();
Exemplo n.º 12
0
<?php

/**
 * Handle linkback() response from LinkedIn.
 */
if (array_key_exists('stateid', $_REQUEST)) {
    $stateId = $_REQUEST['stateid'];
} else {
    throw new Exception('Lost OAuth Client State');
}
$state = SimpleSAML_Auth_State::loadState($stateId, sspmod_authlinkedin_Auth_Source_LinkedIn::STAGE_INIT);
// http://developer.linkedin.com/docs/DOC-1008#2_Redirect_the_User_to_our_Authorization_Server
if (array_key_exists('oauth_verifier', $_REQUEST)) {
    $state['authlinkedin:oauth_verifier'] = $_REQUEST['oauth_verifier'];
} else {
    throw new Exception('OAuth verifier not returned.');
}
/* Find authentication source. */
assert('array_key_exists(sspmod_authlinkedin_Auth_Source_LinkedIn::AUTHID, $state)');
$sourceId = $state[sspmod_authlinkedin_Auth_Source_LinkedIn::AUTHID];
$source = SimpleSAML_Auth_Source::getById($sourceId);
if ($source === NULL) {
    throw new Exception('Could not find authentication source with id ' . $sourceId);
}
$source->finalStep($state);
SimpleSAML_Auth_Source::completeAuth($state);
Exemplo n.º 13
0
 /**
  * Retrieve a state which has finished processing.
  *
  * @param string $id The state identifier. This can be found in the
  * SimpleSAML_Auth_ProcessingChain::AUTHPARAM request parameter. Please
  * make sure to sanitize it properly by calling the
  * SimpleSAML_Utilities::checkURLAllowed() function with the embedded
  * restart URL, if any. See also SimpleSAML_Utilities::parseStateID().
  */
 public static function fetchProcessedState($id)
 {
     assert('is_string($id)');
     return SimpleSAML_Auth_State::loadState($id, self::COMPLETED_STAGE);
 }
Exemplo n.º 14
0
<?php

/**
 * Handle linkback() response from Facebook.
 */
#if (!array_key_exists('StateID', $_GET))
#	throw new SimpleSAML_Error_BadRequest('Missing StateID to facebook linkback endpoint');
if (!array_key_exists('next', $_GET)) {
    throw new SimpleSAML_Error_BadRequest('Missing parameter [next] to facebook linkback endpoint');
}
$stateID = $_GET['next'];
$state = SimpleSAML_Auth_State::loadState($stateID, sspmod_authfacebook_Auth_Source_Facebook::STAGE_INIT);
/* Find authentication source. */
assert('array_key_exists(sspmod_authfacebook_Auth_Source_Facebook::AUTHID, $state)');
$sourceId = $state[sspmod_authfacebook_Auth_Source_Facebook::AUTHID];
$source = SimpleSAML_Auth_Source::getById($sourceId);
if ($source === NULL) {
    throw new Exception('Could not find authentication source with id ' . $sourceId);
}
$config = SimpleSAML_Configuration::getInstance();
$source->authenticate($state);
SimpleSAML_Auth_Source::completeAuth($state);
Exemplo n.º 15
0
<?php

/**
 * Handle linkback() response from MySpace.
 */
if (array_key_exists('stateid', $_REQUEST)) {
    $stateId = $_REQUEST['stateid'];
} else {
    throw new Exception('State Lost - not returned by MySpace Auth');
}
// sanitize the input
$sid = SimpleSAML_Utilities::parseStateID($stateId);
if (!is_null($sid['url'])) {
    SimpleSAML_Utilities::checkURLAllowed($sid['url']);
}
$state = SimpleSAML_Auth_State::loadState($stateId, sspmod_authmyspace_Auth_Source_MySpace::STAGE_INIT);
if (array_key_exists('oauth_problem', $_REQUEST)) {
    // oauth_problem of 'user_refused' means user chose not to login with MySpace
    if (strcmp($_REQUEST['oauth_problem'], 'user_refused') == 0) {
        $e = new SimpleSAML_Error_UserAborted();
        SimpleSAML_Auth_State::throwException($state, $e);
    }
    // Error
    $e = new SimpleSAML_Error_Error('Authentication failed: ' . $_REQUEST['oauth_problem']);
    SimpleSAML_Auth_State::throwException($state, $e);
}
if (array_key_exists('oauth_verifier', $_REQUEST)) {
    $state['authmyspace:oauth_verifier'] = $_REQUEST['oauth_verifier'];
} else {
    throw new Exception('OAuth verifier not returned.');
}
Exemplo n.º 16
0
<?php

/**
 * Show a 403 Forbidden page about not authorized to access an application.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($id, 'authorize:Authorize');
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'authorize:authorize_403.php');
header('HTTP/1.0 403 Forbidden');
$t->show();
Exemplo n.º 17
0
 /**
  * Handle username-password login request.
  *
  * This function is used by the login form (www/loginuserpass.php) when the user
  * enters a username and password. On success, it will not return. If an error occurs,
  * it will return the error code.
  *
  * @param string $authStateId  The identifier of the authentication state.
  * @param string $username  The username the user wrote.
  * @param string $password  The password the user wrote.
  * @return string Error code in the case of an error.
  */
 public static function handleUserPassLogin($authStateId, $username, $password)
 {
     assert('is_string($authStateId)');
     assert('is_string($username)');
     assert('is_string($password)');
     /* Here we retrieve the state array we saved in the authenticate-function. */
     $state = SimpleSAML_Auth_State::loadState($authStateId, sspmod_authTiqr_Auth_Tiqr::STAGEID);
     /* Retrieve the authentication source we are executing. */
     assert('array_key_exists(self::AUTHID, $state)');
     $source = SimpleSAML_Auth_Source::getById($state[sspmod_authTiqr_Auth_Tiqr::USERPASSSOURCEID]);
     if ($source === NULL) {
         throw new Exception('Could not find authentication source with id ' . $state[sspmod_authTiqr_Auth_Tiqr::USERPASSSOURCEID]);
     }
     /*
      * $source now contains the authentication source on which authenticate()
      * was called. We should call login() on the same authentication source.
      */
     try {
         /* Attempt to log in. */
         $attributes = $source->login($username, $password);
     } catch (SimpleSAML_Error_Error $e) {
         /*
          * Login failed. Return the error code to the login form, so that it
          * can display an error message to the user.
          */
         return $e->getErrorCode();
     }
     /* 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);
 }
Exemplo n.º 18
0
 /**
  * Get available organizations.
  *
  * This function is used by the login form to get the available organizations.
  *
  * @param string $authStateId  The identifier of the authentication state.
  * @return array|NULL  Array of organizations. NULL if the user must enter the
  *         organization as part of the username.
  */
 public static function listOrganizations($authStateId)
 {
     assert('is_string($authStateId)');
     /* Retrieve the authentication state. */
     $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID);
     /* Find authentication source. */
     assert('array_key_exists(self::AUTHID, $state)');
     $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]);
     if ($source === NULL) {
         throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
     }
     $orgMethod = $source->getUsernameOrgMethod();
     if ($orgMethod === 'force') {
         return NULL;
     }
     return $source->getOrganizations();
 }
Exemplo n.º 19
0
 /**
  * Resume authentication process.
  *
  * This function resumes the authentication process after the user has
  * entered his or her credentials.
  *
  * @param array &$state  The authentication state.
  */
 public static function resume()
 {
     /*
      * First we need to restore the $state-array. We should have the identifier for
      * it in the 'State' request parameter.
      */
     if (!isset($_REQUEST['State'])) {
         throw new SimpleSAML_Error_BadRequest('Missing "State" parameter.');
     }
     $stateId = (string) $_REQUEST['State'];
     /*
      * 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($stateId, 'drupalauth:External');
     /*
      * Now we have the $state-array, and can use it to locate the authentication
      * source.
      */
     $source = SimpleSAML_Auth_Source::getById($state['drupalauth: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]);
     }
     /*
      * Make sure that we haven't switched the source type while the
      * user was at the authentication page. This can only happen if we
      * change config/authsources.php while an user is logging in.
      */
     if (!$source instanceof self) {
         throw new SimpleSAML_Error_Exception('Authentication source type changed.');
     }
     /*
      * OK, now we know that our current state is sane. Time to actually log the user in.
      *
      * First we check that the user is acutally logged in, and didn't simply skip the login page.
      */
     $attributes = $source->getUser();
     if ($attributes === NULL) {
         /*
          * The user isn't authenticated.
          *
          * 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.');
     }
     /*
      * So, we have a valid user. Time to resume the authentication process where we
      * paused it in the authenticate()-function above.
      */
     $state['Attributes'] = $attributes;
     SimpleSAML_Auth_Source::completeAuth($state);
     /*
      * The completeAuth-function never returns, so we never get this far.
      */
     assert('FALSE');
 }
Exemplo n.º 20
0
<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
    throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}
$authState = $_REQUEST['AuthState'];
// sanitize the input
$sid = SimpleSAML_Utilities::parseStateID($authState);
if (!is_null($sid['url'])) {
    SimpleSAML_Utilities::checkURLAllowed($sid['url']);
}
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:auth');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
    throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}
try {
    $authSource->postAuth($state);
    /* postAuth() should never return. */
    assert('FALSE');
} catch (SimpleSAML_Error_Exception $e) {
    SimpleSAML_Auth_State::throwException($state, $e);
} catch (Exception $e) {
    SimpleSAML_Auth_State::throwException($state, new SimpleSAML_Error_AuthSource($sourceId, 'Error on OpenID linkback endpoint.', $e));
}
Exemplo n.º 21
0
<?php

/**
 *  * This script displays a page to the user, which requests that the user
 *   * authorizes the release of attributes.
 *    *
 *     * @package simpleSAMLphp
 *      * @version $Id$
 *       */
SimpleSAML_Logger::info('JANUS - Access blocked');
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($id, 'janus:accessblock');
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'janus:accessblock.php', 'janus:accessblock');
$t->data['stateid'] = array('StateId' => $id);
$t->show();
Exemplo n.º 22
0
<?php

/**
 * This is the page the user lands on when choosing "no" in the consent form.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($id, 'consent:request');
$resumeFrom = SimpleSAML_Module::getModuleURL('consent/getconsent.php');
$resumeFrom = SimpleSAML_Utilities::addURLParameter($resumeFrom, array('StateId' => $id));
$aboutService = NULL;
if (isset($state['Destination']['url.about'])) {
    $aboutService = $state['Destination']['url.about'];
}
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'consent:noconsent.php');
$t->data['dstMetadata'] = $state['Destination'];
$t->data['resumeFrom'] = $resumeFrom;
$t->data['aboutService'] = $aboutService;
$t->show();
Exemplo n.º 23
0
$spMetadata = $source->getMetadata();
sspmod_saml_Message::validateMessage($idpMetadata, $spMetadata, $message);
$destination = $message->getDestination();
//if ($destination !== NULL && $destination !== SimpleSAML_Utilities::selfURLNoQuery()) {
//	throw new SimpleSAML_Error_Exception('Destination in logout message is wrong.');
//}
if ($message instanceof SAML2_LogoutResponse) {
    $relayState = $message->getRelayState();
    if ($relayState === NULL) {
        /* Somehow, our RelayState has been lost. */
        throw new SimpleSAML_Error_BadRequest('Missing RelayState in logout response.');
    }
    if (!$message->isSuccess()) {
        SimpleSAML_Logger::warning('Unsuccessful logout. Status was: ' . sspmod_saml_Message::getResponseError($message));
    }
    $state = SimpleSAML_Auth_State::loadState($relayState, 'saml:slosent');
    SimpleSAML_Auth_Source::completeLogout($state);
} elseif ($message instanceof SAML2_LogoutRequest) {
    SimpleSAML_Logger::debug('module/saml2/sp/logout: Request from ' . $idpEntityId);
    SimpleSAML_Logger::stats('saml20-idp-SLO idpinit ' . $spEntityId . ' ' . $idpEntityId);
    if ($message->isNameIdEncrypted()) {
        try {
            $keys = sspmod_saml_Message::getDecryptionKeys($srcMetadata, $dstMetadata);
        } catch (Exception $e) {
            throw new SimpleSAML_Error_Exception('Error decrypting NameID: ' . $e->getMessage());
        }
        $lastException = NULL;
        foreach ($keys as $i => $key) {
            try {
                $message->decryptNameId($key);
                SimpleSAML_Logger::debug('Decryption with key #' . $i . ' succeeded.');
Exemplo n.º 24
0
<?php

/**
 *
 *
 * @author Mathias Meisfjordskar, University of Oslo.
 *         <*****@*****.**>
 * @package simpleSAMLphp
 */
$state = SimpleSAML_Auth_State::loadState($_REQUEST['AuthState'], sspmod_negotiate_Auth_Source_Negotiate::STAGEID);
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$idpid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted', 'metaindex');
$idpmeta = $metadata->getMetaData($idpid, 'saml20-idp-hosted');
if (isset($idpmeta['auth'])) {
    $source = SimpleSAML_Auth_Source::getById($idpmeta['auth']);
    if ($source === NULL) {
        throw new SimpleSAML_Error_BadRequest('Invalid AuthId "' . $idpmeta['auth'] . '" - not found.');
    }
    $session = SimpleSAML_Session::getSessionFromRequest();
    $session->setData('negotiate:disable', 'session', FALSE, 24 * 60 * 60);
    SimpleSAML_Logger::debug('Negotiate(retry) - session enabled, retrying.');
    $source->authenticate($state);
    assert('FALSE');
} else {
    SimpleSAML_Logger::error('Negotiate - retry - no "auth" parameter found in IdP metadata.');
    assert('FALSE');
}
Exemplo n.º 25
0
<?php

/**
 * Handler for response from IdP discovery service.
 */
if (!array_key_exists('AuthID', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing AuthID to discovery service response handler');
}
if (!array_key_exists('idpentityid', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing idpentityid to discovery service response handler');
}
$stateID = $_REQUEST['AuthID'];
// sanitize the input
$sid = SimpleSAML_Utilities::parseStateID($stateID);
if (!is_null($sid['url'])) {
    SimpleSAML_Utilities::checkURLAllowed($sid['url']);
}
$state = SimpleSAML_Auth_State::loadState($stateID, 'saml:sp:sso');
/* Find authentication source. */
assert('array_key_exists("saml:sp:AuthId", $state)');
$sourceId = $state['saml:sp:AuthId'];
$source = SimpleSAML_Auth_Source::getById($sourceId);
if ($source === NULL) {
    throw new Exception('Could not find authentication source with id ' . $sourceId);
}
if (!$source instanceof sspmod_saml_Auth_Source_SP) {
    throw new SimpleSAML_Error_Exception('Source type changed?');
}
$source->startSSO($_REQUEST['idpentityid'], $state);
Exemplo n.º 26
0
 /**
  * Handle login request.
  *
  * This function is used by the login form (core/www/loginuserpass.php) when the user
  * enters a username and password. On success, it will not return. On wrong
  * username/password failure, it will return the error code. Other failures will throw an
  * exception.
  *
  * @param string $authStateId  The identifier of the authentication state.
  * @param string $otp  The one time password entered-
  * @return string  Error code in the case of an error.
  */
 public static function handleLogin($authStateId, $otp)
 {
     assert('is_string($authStateId)');
     assert('is_string($otp)');
     /* Retrieve the authentication state. */
     $state = SimpleSAML_Auth_State::loadState($authStateId, self::STAGEID);
     /* Find authentication source. */
     assert('array_key_exists(self::AUTHID, $state)');
     $source = SimpleSAML_Auth_Source::getById($state[self::AUTHID]);
     if ($source === NULL) {
         throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
     }
     try {
         /* Attempt to log in. */
         $attributes = $source->login($otp);
     } catch (SimpleSAML_Error_Error $e) {
         /* An error occurred during login. Check if it is because of the wrong
          * username/password - if it is, we pass that error up to the login form,
          * if not, we let the generic error handler deal with it.
          */
         if ($e->getErrorCode() === 'WRONGUSERPASS') {
             return 'WRONGUSERPASS';
         }
         /* Some other error occurred. Rethrow exception and let the generic error
          * handler deal with it.
          */
         throw $e;
     }
     $state['Attributes'] = $attributes;
     SimpleSAML_Auth_Source::completeAuth($state);
 }
Exemplo n.º 27
0
<?php

/**
 * Show a 403 Forbidden page about not authorized to access an application.
 *
 * @package SimpleSAMLphp
 */
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$state = SimpleSAML_Auth_State::loadState($_REQUEST['StateId'], 'authorize:Authorize');
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'authorize:authorize_403.php');
if (isset($state['Source']['auth'])) {
    $t->data['LogoutURL'] = SimpleSAML\Module::getModuleURL('core/authenticate.php', array('as' => $state['Source']['auth'])) . "&logout";
}
header('HTTP/1.0 403 Forbidden');
$t->show();
Exemplo n.º 28
0
 /**
  * Retrieve state by ID.
  *
  * @param string $stateId  The state ID.
  * @return array  The state array.
  */
 public function loadState($stateId)
 {
     assert('is_string($stateId)');
     return SimpleSAML_Auth_State::loadState($stateId, 'openidProvider:resumeState');
 }
Exemplo n.º 29
0
if (!isset($_REQUEST['id'])) {
    throw new SimpleSAML_Error_BadRequest('Missing required parameter: id');
}
if (isset($_REQUEST['type'])) {
    $type = (string) $_REQUEST['type'];
    if (!in_array($type, array('init', 'js', 'nojs', 'embed'), TRUE)) {
        throw new SimpleSAML_Error_BadRequest('Invalid value for type.');
    }
} else {
    $type = 'init';
}
if ($type !== 'embed' && $type !== 'async') {
    SimpleSAML_Logger::stats('slo-iframe ' . $type);
    SimpleSAML_Stats::log('core:idp:logout-iframe:page', array('type' => $type));
}
$state = SimpleSAML_Auth_State::loadState($_REQUEST['id'], 'core:Logout-IFrame');
$idp = SimpleSAML_IdP::getByState($state);
if ($type !== 'init') {
    /* Update association state. */
    $associations = $idp->getAssociations();
    foreach ($state['core:Logout-IFrame:Associations'] as $assocId => &$sp) {
        $spId = sha1($assocId);
        /* Move SPs from 'onhold' to 'inprogress'. */
        if ($sp['core:Logout-IFrame:State'] === 'onhold') {
            $sp['core:Logout-IFrame:State'] = 'inprogress';
        }
        /* Check for update through request. */
        if (isset($_REQUEST[$spId])) {
            $s = $_REQUEST[$spId];
            if ($s == 'completed' || $s == 'failed') {
                $sp['core:Logout-IFrame:State'] = $s;
Exemplo n.º 30
0
 *
 * @author Lorenzo Gil, Yaco Sistemas S.L.
 * @package simpleSAMLphp
 * @version $Id$
 */
if (!array_key_exists('AuthState', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing AuthState parameter.');
}
$authStateId = $_REQUEST['AuthState'];
// sanitize the input
$sid = SimpleSAML_Utilities::parseStateID($authStateId);
if (!is_null($sid['url'])) {
    SimpleSAML_Utilities::checkURLAllowed($sid['url']);
}
/* Retrieve the authentication state. */
$state = SimpleSAML_Auth_State::loadState($authStateId, sspmod_multiauth_Auth_Source_MultiAuth::STAGEID);
if (array_key_exists("SimpleSAML_Auth_Default.id", $state)) {
    $authId = $state["SimpleSAML_Auth_Default.id"];
    $as = SimpleSAML_Auth_Source::getById($authId);
} else {
    $as = NULL;
}
$source = NULL;
if (array_key_exists('source', $_REQUEST)) {
    $source = $_REQUEST['source'];
} else {
    foreach ($_REQUEST as $k => $v) {
        $k = explode('-', $k, 2);
        if (count($k) === 2 && $k[0] === 'src') {
            $source = base64_decode($k[1]);
        }