/** * When the process logic determines that the user is not * authorized for this service, then forward the user to * an 403 unauthorized page. * * Separated this code into its own method so that child * classes can override it and change the action. Forward * thinking in case a "chained" ACL is needed, more complex * permission logic. * * @param array $request */ protected function unauthorized(&$request) { SimpleSAML_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('saml/sp/wrong_authncontextclassref.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id)); }
/** * Start the logout operation. * * @param array &$state The logout state. * @param string|NULL $assocId The SP we are logging out from. */ public function startLogout(array &$state, $assocId) { assert('is_string($assocId) || is_null($assocId)'); $associations = $this->idp->getAssociations(); if (count($associations) === 0) { $this->idp->finishLogout($state); } foreach ($associations as $id => &$association) { $idp = SimpleSAML_IdP::getByState($association); $association['core:Logout-IFrame:Name'] = $idp->getSPName($id); $association['core:Logout-IFrame:State'] = 'onhold'; } $state['core:Logout-IFrame:Associations'] = $associations; if (!is_null($assocId)) { $spName = $this->idp->getSPName($assocId); if ($spName === NULL) { $spName = array('en' => $assocId); } $state['core:Logout-IFrame:From'] = $spName; } else { $state['core:Logout-IFrame:From'] = NULL; } $params = array('id' => SimpleSAML_Auth_State::saveState($state, 'core:Logout-IFrame')); if (isset($state['core:Logout-IFrame:InitType'])) { $params['type'] = $state['core:Logout-IFrame:InitType']; } $url = SimpleSAML_Module::getModuleURL('core/idp/logout-iframe.php', $params); SimpleSAML_Utilities::redirectTrustedURL($url); }
/** * Process a authentication response. * * This function checks how long it is since the last time the user was authenticated. * If it is to short a while since, we will show a warning to the user. * * @param array $state The state of the response. */ public function process(&$state) { assert('is_array($state)'); if (!array_key_exists('PreviousSSOTimestamp', $state)) { /* * No timestamp from the previous SSO to this SP. This is the first * time during this session. */ return; } $timeDelta = time() - $state['PreviousSSOTimestamp']; if ($timeDelta >= 10) { /* At least 10 seconds since last attempt. */ return; } if (array_key_exists('Destination', $state) && array_key_exists('entityid', $state['Destination'])) { $entityId = $state['Destination']['entityid']; } else { $entityId = 'UNKNOWN'; } SimpleSAML_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_Utilities::redirectTrustedURL($url, array('StateId' => $id)); }
function handleResponse() { try { $binding = SAML2_Binding::getCurrentBinding(); $response = $binding->receive(); } catch (Exception $e) { return; } SimpleSAML_Logger::debug('attributequery - received message.'); if (!$response instanceof SAML2_Response) { throw new SimpleSAML_Error_Exception('Unexpected message received to attribute query example.'); } $idpEntityId = $response->getIssuer(); if ($idpEntityId === NULL) { throw new SimpleSAML_Error_Exception('Missing issuer in response.'); } $idpMetadata = $GLOBALS['metadata']->getMetaDataConfig($idpEntityId, 'saml20-idp-remote'); $spMetadata = $GLOBALS['metadata']->getMetaDataConfig($GLOBALS['spEntityId'], 'saml20-sp-hosted'); $assertion = sspmod_saml_Message::processResponse($spMetadata, $idpMetadata, $response); if (count($assertion) > 1) { throw new SimpleSAML_Error_Exception('More than one assertion in received response.'); } $assertion = $assertion[0]; $dataId = $response->getRelayState(); if ($dataId === NULL) { throw new SimpleSAML_Error_Exception('RelayState was lost during request.'); } $data = $GLOBALS['session']->getData('attributequeryexample:data', $dataId); $data['attributes'] = $assertion->getAttributes(); $GLOBALS['session']->setData('attributequeryexample:data', $dataId, $data, 3600); SimpleSAML_Utilities::redirectTrustedURL(SimpleSAML_Utilities::selfURLNoQuery(), array('dataId' => $dataId)); }
/** * Log-in using Google OAuth2Login (OpenID Connect) platform * Documentation at : https://developers.google.com/accounts/docs/OAuth2Login * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { $state[self::AUTHID] = $this->authId; $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); $this->client->getAuth()->setState($stateID); $authUrl = $this->client->createAuthUrl(); SimpleSAML_Utilities::redirectTrustedURL($authUrl); }
public function authenticate(&$state) { assert('is_array($state)'); /* 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); $url = SimpleSAML_Module::getModuleURL('InfoCard/login-infocard.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('AuthState' => $id)); }
/** * Initialize processing of the redirect test. * * @param array &$state The state we should update. */ public function process(&$state) { assert('is_array($state)'); assert('array_key_exists("Attributes", $state)'); /* To check whether the state is saved correctly. */ $state['Attributes']['RedirectTest1'] = array('OK'); /* Save state and redirect. */ $id = SimpleSAML_Auth_State::saveState($state, 'exampleauth:redirectfilter-test'); $url = SimpleSAML_Module::getModuleURL('exampleauth/redirecttest.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id)); }
/** * Process a authentication response. * * This function saves the state, and redirects the user to the page where the user * can authorize the release of the attributes. * * @param array $state The state of the response. */ public function process(&$state) { assert('is_array($state)'); if (isset($state['isPassive']) && $state['isPassive'] === TRUE) { /* We have a passive request. Skip the warning. */ return; } /* Save state and redirect. */ $id = SimpleSAML_Auth_State::saveState($state, 'warning:request'); $url = SimpleSAML_Module::getModuleURL('preprodwarning/showwarning.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id)); }
/** * Log-in using LiveID platform * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { assert('is_array($state)'); /* We are going to need the authId in order to retrieve this authentication source later. */ $state[self::AUTHID] = $this->authId; $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); SimpleSAML_Logger::debug('authwindowslive auth state id = ' . $stateID); // Authenticate the user // Documentation at: http://msdn.microsoft.com/en-us/library/ff749771.aspx $authorizeURL = 'https://consent.live.com/Connect.aspx' . '?wrap_client_id=' . $this->key . '&wrap_callback=' . urlencode(SimpleSAML_Module::getModuleUrl('authwindowslive') . '/linkback.php') . '&wrap_client_state=' . urlencode($stateID) . '&wrap_scope=WL_Profiles.View,Messenger.SignIn'; SimpleSAML_Utilities::redirectTrustedURL($authorizeURL); }
/** * Initiate authentication. * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { $state['aselect::authid'] = $this->authId; $id = SimpleSAML_Auth_State::saveState($state, 'aselect:login', true); try { $app_url = SimpleSAML_Module::getModuleURL('aselect/credentials.php', array('ssp_state' => $id)); $as_url = $this->request_authentication($app_url); SimpleSAML_Utilities::redirectTrustedURL($as_url); } catch (Exception $e) { // attach the exception to the state SimpleSAML_Auth_State::throwException($state, $e); } }
/** * Log-in using Facebook platform * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { assert('is_array($state)'); /* We are going to need the authId in order to retrieve this authentication source later. */ $state[self::AUTHID] = $this->authId; $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); $facebook = new sspmod_authfacebook_Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state); $facebook->destroySession(); $linkback = SimpleSAML_Module::getModuleURL('authfacebook/linkback.php', array('AuthState' => $stateID)); $url = $facebook->getLoginUrl(array('redirect_uri' => $linkback, 'scope' => $this->req_perms)); SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); SimpleSAML_Utilities::redirectTrustedURL($url); }
/** * Finish login operation. * * This helper function finishes a login operation and redirects the user back to the page which * requested the login. * * @param array $authProcState The state of the authentication process. */ function finishLogin($authProcState) { assert('is_array($authProcState)'); assert('array_key_exists("Attributes", $authProcState)'); assert('array_key_exists("core:shib13-sp:NameID", $authProcState)'); assert('array_key_exists("core:shib13-sp:SessionIndex", $authProcState)'); assert('array_key_exists("core:shib13-sp:TargetURL", $authProcState)'); assert('array_key_exists("Source", $authProcState)'); assert('array_key_exists("entityid", $authProcState["Source"])'); $authData = array('Attributes' => $authProcState['Attributes'], 'saml:sp:NameID' => $authProcState['core:shib13-sp:NameID'], 'saml:sp:SessionIndex' => $authProcState['core:shib13-sp:SessionIndex'], 'saml:sp:IdP' => $authProcState['Source']['entityid']); global $session; $session->doLogin('shib13', $authData); SimpleSAML_Utilities::redirectTrustedURL($authProcState['core:shib13-sp:TargetURL']); }
/** * Picks the next SP and issues a logout request. * * This function never returns. * * @param array &$state The logout state. */ private function logoutNextSP(array &$state) { $association = array_pop($state['core:LogoutTraditional:Remaining']); if ($association === NULL) { $this->idp->finishLogout($state); } $relayState = SimpleSAML_Auth_State::saveState($state, 'core:LogoutTraditional', TRUE); $id = $association['id']; SimpleSAML_Logger::info('Logging out of ' . var_export($id, TRUE) . '.'); try { $idp = SimpleSAML_IdP::getByState($association); $url = call_user_func(array($association['Handler'], 'getLogoutURL'), $idp, $association, $relayState); SimpleSAML_Utilities::redirectTrustedURL($url); } catch (Exception $e) { SimpleSAML_Logger::warning('Unable to initialize logout to ' . var_export($id, TRUE) . '.'); $this->idp->terminateAssociation($id); $state['core:Failed'] = TRUE; /* Try the next SP. */ $this->logoutNextSP($state); assert('FALSE'); } }
<?php require_once '../_include.php'; $config = SimpleSAML_Configuration::getInstance(); $session = SimpleSAML_Session::getInstance(); if (!$session->isValid('wsfed')) { SimpleSAML_Utilities::redirectTrustedURL('/' . $config->getBaseURL() . 'wsfed/sp/initSSO.php', array('RelayState' => SimpleSAML_Utilities::selfURL())); } $attributes = $session->getAuthData('wsfed', 'Attributes'); $t = new SimpleSAML_XHTML_Template($config, 'status.php', 'attributes'); $t->data['header'] = '{status:header_wsfed}'; $t->data['remaining'] = $session->getAuthData('wsfed', 'Expire') - time(); $t->data['sessionsize'] = $session->getSize(); $t->data['attributes'] = $attributes; $t->data['logouturl'] = '/' . $config->getBaseURL() . 'wsfed/sp/initSLO.php?RelayState=/' . $config->getBaseURL() . 'logout.php'; $t->show();
/** * Process a authentication response * * This function saves the state, and redirects the user to the page where * the user can authorize the release of the attributes. * If storage is used and the consent has already been given the user is * passed on. * * @param array &$state The state of the response. * * @return void */ public function process(&$state) { assert('is_array($state)'); assert('array_key_exists("UserID", $state)'); assert('array_key_exists("Destination", $state)'); assert('array_key_exists("entityid", $state["Destination"])'); assert('array_key_exists("metadata-set", $state["Destination"])'); assert('array_key_exists("entityid", $state["Source"])'); assert('array_key_exists("metadata-set", $state["Source"])'); $spEntityId = $state['Destination']['entityid']; $idpEntityId = $state['Source']['entityid']; $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); /** * If the consent module is active on a bridge $state['saml:sp:IdP'] * will contain an entry id for the remote IdP. If not, then the * consent module is active on a local IdP and nothing needs to be * done. */ if (isset($state['saml:sp:IdP'])) { $idpEntityId = $state['saml:sp:IdP']; $idpmeta = $metadata->getMetaData($idpEntityId, 'saml20-idp-remote'); $state['Source'] = $idpmeta; } $statsData = array('spEntityID' => $spEntityId); // Do not use consent if disabled if (isset($state['Source']['consent.disable']) && self::checkDisable($state['Source']['consent.disable'], $spEntityId)) { SimpleSAML_Logger::debug('Consent: Consent disabled for entity ' . $spEntityId . ' with IdP ' . $idpEntityId); SimpleSAML_Stats::log('consent:disabled', $statsData); return; } if (isset($state['Destination']['consent.disable']) && self::checkDisable($state['Destination']['consent.disable'], $idpEntityId)) { SimpleSAML_Logger::debug('Consent: Consent disabled for entity ' . $spEntityId . ' with IdP ' . $idpEntityId); SimpleSAML_Stats::log('consent:disabled', $statsData); return; } if ($this->_store !== null) { $source = $state['Source']['metadata-set'] . '|' . $idpEntityId; $destination = $state['Destination']['metadata-set'] . '|' . $spEntityId; $attributes = $state['Attributes']; // Remove attributes that do not require consent foreach ($attributes as $attrkey => $attrval) { if (in_array($attrkey, $this->_noconsentattributes)) { unset($attributes[$attrkey]); } } SimpleSAML_Logger::debug('Consent: userid: ' . $state['UserID']); SimpleSAML_Logger::debug('Consent: source: ' . $source); SimpleSAML_Logger::debug('Consent: destination: ' . $destination); $userId = self::getHashedUserID($state['UserID'], $source); $targetedId = self::getTargetedID($state['UserID'], $source, $destination); $attributeSet = self::getAttributeHash($attributes, $this->_includeValues); SimpleSAML_Logger::debug('Consent: hasConsent() [' . $userId . '|' . $targetedId . '|' . $attributeSet . ']'); try { if ($this->_store->hasConsent($userId, $targetedId, $attributeSet)) { // Consent already given SimpleSAML_Logger::stats('Consent: Consent found'); SimpleSAML_Stats::log('consent:found', $statsData); return; } SimpleSAML_Logger::stats('Consent: Consent notfound'); SimpleSAML_Stats::log('consent:notfound', $statsData); $state['consent:store'] = $this->_store; $state['consent:store.userId'] = $userId; $state['consent:store.destination'] = $targetedId; $state['consent:store.attributeSet'] = $attributeSet; } catch (Exception $e) { SimpleSAML_Logger::error('Consent: Error reading from storage: ' . $e->getMessage()); SimpleSAML_Logger::stats('Consent: Failed'); SimpleSAML_Stats::log('consent:failed', $statsData); } } else { SimpleSAML_Logger::stats('Consent: No storage'); SimpleSAML_Stats::log('consent:nostorage', $statsData); } $state['consent:focus'] = $this->_focus; $state['consent:checked'] = $this->_checked; $state['consent:hiddenAttributes'] = $this->_hiddenAttributes; $state['consent:noconsentattributes'] = $this->_noconsentattributes; $state['consent:showNoConsentAboutService'] = $this->_showNoConsentAboutService; // User interaction nessesary. Throw exception on isPassive request if (isset($state['isPassive']) && $state['isPassive'] == true) { SimpleSAML_Stats::log('consent:nopassive', $statsData); throw new SimpleSAML_Error_NoPassive('Unable to give consent on passive request.'); } // Save state and redirect $id = SimpleSAML_Auth_State::saveState($state, 'consent:request'); $url = SimpleSAML_Module::getModuleURL('consent/getconsent.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id)); }
* Load the RelayState argument. The RelayState argument contains the address * we should redirect the user to after a successful authentication. */ if (!array_key_exists('RelayState', $_REQUEST)) { throw new SimpleSAML_Error_Error('NORELAYSTATE'); } $relaystate = SimpleSAML_Utilities::checkURLAllowed($_REQUEST['RelayState']); if ($username = $_POST['username']) { try { $ldap = new SimpleSAML_Auth_LDAP($ldapconfig['servers'], $ldapconfig['enable_tls']); $attributes = $ldap->validate($ldapconfig, $username, $_POST['password']); if ($attributes === FALSE) { $error = "LDAP_INVALID_CREDENTIALS"; } else { $session->doLogin('login-wayf-ldap'); $session->setAttributes($attributes); $session->setNameID(array('value' => SimpleSAML_Utilities::generateID(), 'Format' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient')); SimpleSAML_Utilities::redirectTrustedURL($relaystate); } } catch (Exception $e) { throw new SimpleSAML_Error_Error('LDAPERROR', $e); } } $t = new SimpleSAML_XHTML_Template($config, $ldapconfig['template']); $t->data['header'] = 'simpleSAMLphp: Enter username and password'; $t->data['relaystate'] = htmlspecialchars($relaystate); $t->data['error'] = $error; if (isset($error)) { $t->data['username'] = htmlspecialchars($username); } $t->show();
/** * Redirect to a URL after logout. * * This function never returns. * * @param array &$state The logout state from doLogoutRedirect(). */ public static function finishLogoutRedirect(SimpleSAML_IdP $idp, array $state) { assert('isset($state["core:Logout:URL"])'); SimpleSAML_Utilities::redirectTrustedURL($state['core:Logout:URL']); assert('FALSE'); }
<?php require_once '_include.php'; SimpleSAML_Utilities::redirectTrustedURL(SimpleSAML_Module::getModuleURL('core/frontpage_welcome.php'));
$discourl = $spmetadata['idpdisco.url']; } elseif ($config->getString('idpdisco.url.saml20', NULL) !== NULL) { $discourl = $config->getString('idpdisco.url.saml20'); } else { $discourl = SimpleSAML_Utilities::getBaseURL() . 'saml2/sp/idpdisco.php'; } $extDiscoveryStorage = $config->getString('idpdisco.extDiscoveryStorage', NULL); if ($extDiscoveryStorage !== NULL) { SimpleSAML_Utilities::redirectTrustedURL($extDiscoveryStorage, array('entityID' => $spentityid, 'return' => SimpleSAML_Utilities::addURLparameter($discourl, array('return' => SimpleSAML_Utilities::selfURL(), 'remember' => 'true', 'entityID' => $spentityid, 'returnIDParam' => 'idpentityid')), 'returnIDParam' => 'idpentityid', 'isPassive' => 'true')); } $discoparameters = array('entityID' => $spentityid, 'return' => SimpleSAML_Utilities::selfURL(), 'returnIDParam' => 'idpentityid'); $discoparameters['isPassive'] = $isPassive; if (sizeof($reachableIDPs) > 0) { $discoparameters['IDPList'] = $reachableIDPs; } SimpleSAML_Utilities::redirectTrustedURL($discourl, $discoparameters); } /* * Create and send authentication request to the IdP. */ try { $spMetadata = $metadata->getMetaDataConfig($spentityid, 'saml20-sp-hosted'); $idpMetadata = $metadata->getMetaDataConfig($idpentityid, 'saml20-idp-remote'); $ar = sspmod_saml_Message::buildAuthnRequest($spMetadata, $idpMetadata); $assertionConsumerServiceURL = $metadata->getGenerated('AssertionConsumerService', 'saml20-sp-hosted'); $ar->setAssertionConsumerServiceURL($assertionConsumerServiceURL); $ar->setRelayState($returnTo); if ($isPassive) { $ar->setIsPassive(TRUE); } if ($forceAuthn) {
} else { $ownPage = FALSE; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($ownPage) { foreach ($_POST as $k => $v) { $op = explode('_', $k, 2); if (count($op) == 1 || $op[0] !== 'remove') { continue; } $site = $op[1]; $site = pack("H*", $site); $server->removeTrustRoot($identity, $site); } } SimpleSAML_Utilities::redirectTrustedURL($identity); } if ($ownPage) { $trustedSites = $server->getTrustRoots($identity); } else { $trustedSites = array(); } $userBase = SimpleSAML_Module::getModuleURL('openidProvider/user.php'); $xrds = SimpleSAML_Module::getModuleURL('openidProvider/xrds.php'); if ($userId !== FALSE) { $xrds = SimpleSAML_Utilities::addURLparameter($xrds, array('user' => $userId)); } $as = $server->getAuthSource(); $t = new SimpleSAML_XHTML_Template($globalConfig, 'openidProvider:user.tpl.php'); $t->data['identity'] = $identity; $t->data['loggedInAs'] = $server->getUserId();
/** * When the process logic determines that the user is not * authorized for this service, then forward the user to * an 403 unauthorized page. * * Separated this code into its own method so that child * classes can override it and change the action. Forward * thinking in case a "chained" ACL is needed, more complex * permission logic. * * @param array $request */ protected function unauthorized(&$request) { /* Save state and redirect to 403 page. */ $id = SimpleSAML_Auth_State::saveState($request, 'authorize:Authorize'); $url = SimpleSAML_Module::getModuleURL('authorize/authorize_403.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id)); }
/** * Throw exception to the state exception handler. * * @param array $state The state array. * @param SimpleSAML_Error_Exception $exception The exception. */ public static function throwException($state, SimpleSAML_Error_Exception $exception) { assert('is_array($state)'); if (array_key_exists(self::EXCEPTION_HANDLER_URL, $state)) { /* Save the exception. */ $state[self::EXCEPTION_DATA] = $exception; $id = self::saveState($state, self::EXCEPTION_STAGE); /* Redirect to the exception handler. */ SimpleSAML_Utilities::redirectTrustedURL($state[self::EXCEPTION_HANDLER_URL], array(self::EXCEPTION_PARAM => $id)); } elseif (array_key_exists(self::EXCEPTION_HANDLER_FUNC, $state)) { /* Call the exception handler. */ $func = $state[self::EXCEPTION_HANDLER_FUNC]; assert('is_callable($func)'); call_user_func($func, $exception, $state); assert(FALSE); } else { /* * No exception handler is defined for the current state. */ throw $exception; } }
/** * Send an authentication request to the OpenID provider. * * @param array &$state The state array. * @param string $openid The OpenID we should try to authenticate with. */ public function doAuth(array &$state, $openid) { assert('is_string($openid)'); $stateId = SimpleSAML_Auth_State::saveState($state, 'openid:auth'); $consumer = $this->getConsumer($state); // Begin the OpenID authentication process. $auth_request = $consumer->begin($openid); // No auth request means we can't begin OpenID. if (!$auth_request) { throw new SimpleSAML_Error_BadRequest('Not a valid OpenID: ' . var_export($openid, TRUE)); } $sreg_request = Auth_OpenID_SRegRequest::build($this->requiredAttributes, $this->optionalAttributes); if ($sreg_request) { $auth_request->addExtension($sreg_request); } // Create attribute request object $ax_attribute = array(); foreach ($this->requiredAXAttributes as $attr) { $ax_attribute[] = Auth_OpenID_AX_AttrInfo::make($attr, 1, true); } foreach ($this->optionalAXAttributes as $attr) { $ax_attribute[] = Auth_OpenID_AX_AttrInfo::make($attr, 1, false); } if (count($ax_attribute) > 0) { // Create AX fetch request $ax_request = new Auth_OpenID_AX_FetchRequest(); // Add attributes to AX fetch request foreach ($ax_attribute as $attr) { $ax_request->add($attr); } // Add AX fetch request to authentication request $auth_request->addExtension($ax_request); } foreach ($this->extensionArgs as $ext_ns => $ext_arg) { if (is_array($ext_arg)) { foreach ($ext_arg as $ext_key => $ext_value) { $auth_request->addExtensionArg($ext_ns, $ext_key, $ext_value); } } } // Redirect the user to the OpenID server for authentication. // Store the token for this authentication so we can verify the // response. // For OpenID 1, send a redirect. For OpenID 2, use a Javascript form // to send a POST request to the server or use redirect if // prefer_http_redirect is enabled and redirect URL size // is less than 2049 $should_send_redirect = $auth_request->shouldSendRedirect(); if ($this->preferHttpRedirect || $should_send_redirect) { $redirect_url = $auth_request->redirectURL($this->getTrustRoot(), $this->getReturnTo($stateId)); // If the redirect URL can't be built, display an error message. if (Auth_OpenID::isFailure($redirect_url)) { throw new SimpleSAML_Error_AuthSource($this->authId, 'Could not redirect to server: ' . var_export($redirect_url->message, TRUE)); } // For OpenID 2 failover to POST if redirect URL is longer than 2048 if ($should_send_redirect || strlen($redirect_url) <= 2048) { SimpleSAML_Utilities::redirectTrustedURL($redirect_url); assert('FALSE'); } } // Generate form markup and render it. $form_id = 'openid_message'; $form_html = $auth_request->formMarkup($this->getTrustRoot(), $this->getReturnTo($stateId), FALSE, array('id' => $form_id)); // Display an error if the form markup couldn't be generated; otherwise, render the HTML. if (Auth_OpenID::isFailure($form_html)) { throw new SimpleSAML_Error_AuthSource($this->authId, 'Could not redirect to server: ' . var_export($form_html->message, TRUE)); } else { echo '<html><head><title>OpenID transaction in progress</title></head> <body onload=\'document.getElementById("' . $form_id . '").submit()\'>' . $form_html . '</body></html>'; exit; } }
/** * Apply filter * * @param array &$state The current state. */ public function process(&$state) { /* * UTC format: 20090527080352Z */ $netId = $state['Attributes'][$this->netid_attr][0]; $expireOnDate = strtotime($state['Attributes'][$this->expirydate_attr][0]); if (self::shWarning($state, $expireOnDate, $this->warndaysbefore)) { assert('is_array($state)'); if (isset($state['isPassive']) && $state['isPassive'] === TRUE) { /* We have a passive request. Skip the warning. */ return; } SimpleSAML_Logger::warning('expirycheck: NetID ' . $netId . ' is about to expire!'); /* Save state and redirect. */ $state['expireOnDate'] = date($this->date_format, $expireOnDate); $state['netId'] = $netId; $id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:about2expire'); $url = SimpleSAML_Module::getModuleURL('expirycheck/about2expire.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id)); } if (!self::checkDate($expireOnDate)) { SimpleSAML_Logger::error('expirycheck: NetID ' . $netId . ' has expired [' . date($this->date_format, $expireOnDate) . ']. Access denied!'); $globalConfig = SimpleSAML_Configuration::getInstance(); /* Save state and redirect. */ $state['expireOnDate'] = date($this->date_format, $expireOnDate); $state['netId'] = $netId; $id = SimpleSAML_Auth_State::saveState($state, 'expirywarning:expired'); $url = SimpleSAML_Module::getModuleURL('expirycheck/expired.php'); SimpleSAML_Utilities::redirectTrustedURL($url, array('StateId' => $id)); } }
/** * Handles a request to this discovery service. * * The IdP disco parameters should be set before calling this function. */ public function handleRequest() { $idp = $this->getTargetIdp(); if ($idp !== NULL) { $extDiscoveryStorage = $this->config->getString('idpdisco.extDiscoveryStorage', NULL); if ($extDiscoveryStorage !== NULL) { $this->log('Choice made [' . $idp . '] (Forwarding to external discovery storage)'); SimpleSAML_Utilities::redirectTrustedURL($extDiscoveryStorage, array('entityID' => $this->spEntityId, 'IdPentityID' => $idp, 'returnIDParam' => $this->returnIdParam, 'isPassive' => 'true', 'return' => $this->returnURL)); } else { $this->log('Choice made [' . $idp . '] (Redirecting the user back. returnIDParam=' . $this->returnIdParam . ')'); SimpleSAML_Utilities::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idp)); } return; } if ($this->isPassive) { $this->log('Choice not made. (Redirecting the user back without answer)'); SimpleSAML_Utilities::redirectTrustedURL($this->returnURL); return; } /* No choice made. Show discovery service page. */ $idpList = $this->getIdPList(); $idpList = $this->idplistStructured($this->filterList($idpList)); $preferredIdP = $this->getRecommendedIdP(); $t = new SimpleSAML_XHTML_Template($this->config, 'discopower:disco-tpl.php', 'disco'); $t->data['idplist'] = $idpList; $t->data['preferredidp'] = $preferredIdP; $t->data['return'] = $this->returnURL; $t->data['returnIDParam'] = $this->returnIdParam; $t->data['entityID'] = $this->spEntityId; $t->data['urlpattern'] = htmlspecialchars(SimpleSAML_Utilities::selfURLNoQuery()); $t->data['rememberenabled'] = $this->config->getBoolean('idpdisco.enableremember', FALSE); $t->data['rememberchecked'] = $this->config->getBoolean('idpdisco.rememberchecked', FALSE); $t->data['defaulttab'] = $this->discoconfig->getValue('defaulttab', 0); $t->data['score'] = $this->discoconfig->getValue('score', 'quicksilver'); $t->show(); }
/** * Continues processing of the state. * * This function is used to resume processing by filters which for example needed to show * a page to the user. * * This function will never return. Exceptions thrown during processing will be passed * to whatever exception handler is defined in the state array. * * @param array $state The state we are processing. */ public static function resumeProcessing($state) { assert('is_array($state)'); while (count($state[self::FILTERS_INDEX]) > 0) { $filter = array_shift($state[self::FILTERS_INDEX]); try { $filter->process($state); } catch (SimpleSAML_Error_Exception $e) { SimpleSAML_Auth_State::throwException($state, $e); } catch (Exception $e) { $e = new SimpleSAML_Error_UnserializableException($e); SimpleSAML_Auth_State::throwException($state, $e); } } /* Completed. */ assert('array_key_exists("ReturnURL", $state) || array_key_exists("ReturnCall", $state)'); assert('!array_key_exists("ReturnURL", $state) || !array_key_exists("ReturnCall", $state)'); if (array_key_exists('ReturnURL', $state)) { /* * Save state information, and redirect to the URL specified * in $state['ReturnURL']. */ $id = SimpleSAML_Auth_State::saveState($state, self::COMPLETED_STAGE); SimpleSAML_Utilities::redirectTrustedURL($state['ReturnURL'], array(self::AUTHPARAM => $id)); } else { /* Pass the state to the function defined in $state['ReturnCall']. */ /* We are done with the state array in the session. Delete it. */ SimpleSAML_Auth_State::deleteState($state); $func = $state['ReturnCall']; assert('is_callable($func)'); call_user_func($func, $state); assert(FALSE); } }
/** * Called when logout operation completes. * * This function never returns. * * @param array $state The state after the logout. */ public static function logoutCompleted($state) { assert('is_array($state)'); assert('isset($state["ReturnTo"]) || isset($state["ReturnCallback"])'); if (isset($state['ReturnCallback'])) { call_user_func($state['ReturnCallback'], $state); assert('FALSE'); } else { $params = array(); if (isset($state['ReturnStateParam']) || isset($state['ReturnStateStage'])) { assert('isset($state["ReturnStateParam"]) && isset($state["ReturnStateStage"])'); $stateID = SimpleSAML_Auth_State::saveState($state, $state['ReturnStateStage']); $params[$state['ReturnStateParam']] = $stateID; } SimpleSAML_Utilities::redirectTrustedURL($state['ReturnTo'], $params); } }
/** * Log in using an external authentication helper. * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { assert('is_array($state)'); $attributes = $this->getUser(); if ($attributes !== NULL) { /* * The user is already authenticated. * * Add the users attributes to the $state-array, and return control * to the authentication process. */ $state['Attributes'] = $attributes; return; } /* * The user isn't authenticated. We therefore need to * send the user to the login page. */ /* * First we add the identifier of this authentication source * to the state array, so that we know where to resume. */ $state['exampleauth:AuthID'] = $this->authId; /* * We need to save the $state-array, so that we can resume the * login process after authentication. * * Note the second parameter to the saveState-function. This is a * unique identifier for where the state was saved, and must be used * again when we retrieve the state. * * The reason for it is to prevent * attacks where the user takes a $state-array saved in one location * and restores it in another location, and thus bypasses steps in * the authentication process. */ $stateId = SimpleSAML_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', array('State' => $stateId)); /* * Get the URL of the authentication page. * * Here we use the getModuleURL function again, since the authentication page * 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'); /* * The redirect to the authentication page. * * Note the 'ReturnTo' parameter. This must most likely be replaced with * the real name of the parameter for the login page. */ SimpleSAML_Utilities::redirectTrustedURL($authPage, array('ReturnTo' => $returnTo)); /* * The redirect function never returns, so we never get this far. */ assert('FALSE'); }
/** * Called when logout operation completes. * * This function never returns. * * @param array $state The state after the logout. */ public static function logoutCompleted($state) { assert('is_array($state)'); assert('array_key_exists("SimpleSAML_Auth_Default.ReturnURL", $state)'); $returnURL = $state['SimpleSAML_Auth_Default.ReturnURL']; /* Redirect... */ SimpleSAML_Utilities::redirectTrustedURL($returnURL); }
function casValidate($cas) { $service = SimpleSAML_Utilities::selfURL(); $service = preg_replace("/(\\?|&)?ticket=.*/", "", $service); # always tagged on by cas /** * Got response from CAS server. */ if (isset($_GET['ticket'])) { $ticket = urlencode($_GET['ticket']); #ini_set('default_socket_timeout', 15); if (isset($cas['validate'])) { # cas v1 yes|no\r<username> style $paramPrefix = strpos($cas['validate'], '?') ? '&' : '?'; $result = SimpleSAML_Utilities::fetch($cas['validate'] . $paramPrefix . 'ticket=' . $ticket . '&service=' . urlencode($service)); $res = preg_split("/\r?\n/", $result); if (strcmp($res[0], "yes") == 0) { return array($res[1], array()); } else { throw new Exception("Failed to validate CAS service ticket: {$ticket}"); } } elseif (isset($cas['serviceValidate'])) { # cas v2 xml style $paramPrefix = strpos($cas['serviceValidate'], '?') ? '&' : '?'; $result = SimpleSAML_Utilities::fetch($cas['serviceValidate'] . $paramPrefix . 'ticket=' . $ticket . '&service=' . urlencode($service)); $dom = DOMDocument::loadXML($result); $xPath = new DOMXpath($dom); $xPath->registerNamespace("cas", 'http://www.yale.edu/tp/cas'); $success = $xPath->query("/cas:serviceResponse/cas:authenticationSuccess/cas:user"); if ($success->length == 0) { $failure = $xPath->evaluate("/cas:serviceResponse/cas:authenticationFailure"); throw new Exception("Error when validating CAS service ticket: " . $failure->item(0)->textContent); } else { $attributes = array(); if ($casattributes = $cas['attributes']) { # some has attributes in the xml - attributes is a list of XPath expressions to get them foreach ($casattributes as $name => $query) { $attrs = $xPath->query($query); foreach ($attrs as $attrvalue) { $attributes[$name][] = $attrvalue->textContent; } } } $casusername = $success->item(0)->textContent; return array($casusername, $attributes); } } else { throw new Exception("validate or serviceValidate not specified"); } /** * First request, will redirect the user to the CAS server for authentication. */ } else { SimpleSAML_Logger::info("AUTH - cas-ldap: redirecting to {$cas['login']}"); SimpleSAML_Utilities::redirectTrustedURL($cas['login'], array('service' => $service)); } }