redirectTrustedURL() public static method

This function will use the "HTTP 303 See Other" redirection if the current request used the POST method and the HTTP version is 1.1. Otherwise, a "HTTP 302 Found" redirection will be used. The function will also generate a simple web page with a clickable link to the target URL.
Author: Jaime Perez, UNINETT AS (jaime.perez@uninett.no)
public static redirectTrustedURL ( string $url, string[] $parameters = [] ) : void
$url string The URL we should redirect to. This URL may include query parameters. If this URL is a relative URL (starting with '/'), then it will be turned into an absolute URL by prefixing it with the absolute URL to the root of the website.
$parameters string[] An array with extra query string parameters which should be appended to the URL. The name of the parameter is the array index. The value of the parameter is the value stored in the index. Both the name and the value will be urlencoded. If the value is NULL, then the parameter will be encoded as just the name, without a value.
return void This function never returns.
 /**
  * Log in using an external authentication helper.
  *
  * @param array &$state  Information about the current authentication.
  */
 public function authenticate(&$state)
 {
     $state['openidconnect:AuthID'] = $this->authId;
     $stateId = SimpleSAML_Auth_State::saveState($state, 'openidconnect:Connect', TRUE);
     $info = $this->getConfig($stateId);
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($info["client_info"]["authorization_endpoint"], array("client_id" => $info["client_info"]["client_id"], "redirect_uri" => $info["client_info"]["redirect_uri"], "response_type" => "code", "scope" => $this->scope, "state" => $stateId));
 }
 /**
  * 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\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 }
Example #3
0
 /**
  * Process an authentication response.
  *
  * This function saves the state, and if necessary redirects the user to the page where the user
  * is informed about the expiry date of his/her certificate.
  *
  * @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;
     }
     if (!isset($_SERVER['SSL_CLIENT_CERT']) || $_SERVER['SSL_CLIENT_CERT'] == '') {
         return;
     }
     $client_cert = $_SERVER['SSL_CLIENT_CERT'];
     $client_cert_data = openssl_x509_parse($client_cert);
     if ($client_cert_data == FALSE) {
         SimpleSAML\Logger::error('authX509: invalid cert');
         return;
     }
     $validTo = $client_cert_data['validTo_time_t'];
     $now = time();
     $daysleft = (int) (($validTo - $now) / (24 * 60 * 60));
     if ($daysleft > $this->warndaysbefore) {
         // We have a certificate that will be valid for some time. Skip the warning
         return;
     }
     SimpleSAML\Logger::warning('authX509: user certificate expires in ' . $daysleft . ' days');
     $state['daysleft'] = $daysleft;
     $state['renewurl'] = $this->renewurl;
     /* Save state and redirect. */
     $id = SimpleSAML_Auth_State::saveState($state, 'warning:expire');
     $url = SimpleSAML\Module::getModuleURL('authX509/expirywarning.php');
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 }
 /**
  * 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\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 }
Example #5
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($url);
 }
 /**
  * Log in using an external authentication helper
  *
  * @param array &$state Information about the current authentication
  */
 public function authenticate(&$state)
 {
     $state['dataportenoauth2:AuthID'] = $this->authId;
     $state_id = SimpleSAML_Auth_State::saveState($state, 'dataportenoauth2:Connect', TRUE);
     $info = $this->getConfig($state_id);
     HTTP::redirectTrustedURL($info['auth'], array("client_id" => $info["client_id"], "redirect_uri" => $info["redirect_uri"], "response_type" => "code", "state" => $state_id));
 }
 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\Utils\HTTP::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\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 }
Example #9
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($authorizeURL);
 }
Example #10
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 }
Example #11
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($url);
 }
Example #12
0
 /**
  * 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:
     // https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-protocols-oauth-code/
     $authorizeURL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' . '?client_id=' . $this->key . '&response_type=code' . '&response_mode=query' . '&redirect_uri=' . urlencode(SimpleSAML\Module::getModuleUrl('authwindowslive') . '/linkback.php') . '&state=' . urlencode($stateID) . '&scope=' . urlencode('openid https://graph.microsoft.com/user.read');
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($authorizeURL);
 }
 /**
  * The inner workings of the module. Check client's subnet and redirect
  * to an authentication page protected with "HTTP Negotiate" authentication
  * or a fallback authentication source.
  *
  * @param array &$state Information about the current authentication.
  */
 public function authenticate(&$state)
 {
     assert('is_array($state)');
     $state['negotiateserver:AuthID'] = $this->authId;
     $state['negotiateserver:AuthFallback'] = $this->auth_fallback;
     if (!$this->checkClientSubnet()) {
         $this->fallback($state);
     }
     $stateId = SimpleSAML_Auth_State::saveState($state, 'negotiateserver:Negotiate');
     $returnTo = SimpleSAML\Module::getModuleURL('negotiateserver/resume.php', array('State' => $stateId));
     $authPage = SimpleSAML\Module::getModuleURL('negotiateserver/preauth.php');
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($authPage, array('State' => $stateId, 'ReturnTo' => $returnTo));
     assert('FALSE');
 }
Example #14
0
 /**
  * Initiate authentication.
  *
  * @param array &$state  Information about the current authentication.
  */
 public function authenticate(&$state)
 {
     $state['aselect::authid'] = $this->authId;
     $state['aselect::add_default_attributes'] = $this->add_default_attributes;
     $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\Utils\HTTP::redirectTrustedURL($as_url);
     } catch (Exception $e) {
         // attach the exception to the state
         SimpleSAML_Auth_State::throwException($state, $e);
     }
 }
 /**
  * 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'];
     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);
         HTTP::redirectTrustedURL($url);
     } catch (\Exception $e) {
         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');
     }
 }
Example #16
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($authPage, array('ReturnTo' => $returnTo));
     /*
      * The redirect function never returns, so we never get this far.
      */
     assert('FALSE');
 }
Example #17
0
 public function getAuthorizeRequest($url, $requestToken, $redirect = TRUE, $callback = NULL)
 {
     $params = array('oauth_token' => $requestToken->key);
     if ($callback) {
         $params['oauth_callback'] = $callback;
     }
     $authorizeURL = \SimpleSAML\Utils\HTTP::addURLParameters($url, $params);
     if ($redirect) {
         \SimpleSAML\Utils\HTTP::redirectTrustedURL($authorizeURL);
         exit;
     }
     return $authorizeURL;
 }
Example #18
0
 /**
  * Start an IdP discovery service operation.
  *
  * @param array $state  The state array.
  */
 private function startDisco(array $state)
 {
     $id = SimpleSAML_Auth_State::saveState($state, 'saml:sp:sso');
     $config = SimpleSAML_Configuration::getInstance();
     $discoURL = $this->discoURL;
     if ($discoURL === NULL) {
         /* Fallback to internal discovery service. */
         $discoURL = SimpleSAML\Module::getModuleURL('saml/disco.php');
     }
     $returnTo = SimpleSAML\Module::getModuleURL('saml/sp/discoresp.php', array('AuthID' => $id));
     $params = array('entityID' => $this->entityId, 'return' => $returnTo, 'returnIDParam' => 'idpentityid');
     if (isset($state['saml:IDPList'])) {
         $params['IDPList'] = $state['saml:IDPList'];
     }
     if (isset($state['isPassive']) && $state['isPassive']) {
         $params['isPassive'] = 'true';
     }
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($discoURL, $params);
 }
Example #19
0
 /**
  * Prompt the user with a list of authentication sources.
  *
  * This method saves the information about the configured sources,
  * and redirects to a page where the user must select one of these
  * authentication sources.
  *
  * This method never return. The authentication process is finished
  * in the delegateAuthentication method.
  *
  * @param array &$state	 Information about the current authentication.
  */
 public function authenticate(&$state)
 {
     assert('is_array($state)');
     $state[self::AUTHID] = $this->authId;
     $state[self::SOURCESID] = $this->sources;
     /* Save the $state array, so that we can restore if after a redirect */
     $id = SimpleSAML_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');
     $params = array('AuthState' => $id);
     // Allowes the user to specify the auth souce to be used
     if (isset($_GET['source'])) {
         $params['source'] = $_GET['source'];
     }
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
     /* The previous function never returns, so this code is never
     		executed */
     assert('FALSE');
 }
Example #20
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 }
Example #21
0
 /**
  * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\HTTP::redirectTrustedURL() instead.
  */
 public static function redirectTrustedURL($url, $parameters = array())
 {
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $parameters);
 }
Example #22
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($state['ReturnTo'], $params);
     }
 }
Example #23
0
 /**
  * Initialize login.
  *
  * This function saves the information about the login, and redirects to a
  * login page.
  *
  * @param array &$state  Information about the current authentication.
  */
 public function authenticate(&$state)
 {
     assert('is_array($state)');
     /*
      * Save the identifier of this authentication source, so that we can
      * retrieve it later. This allows us to call the login()-function on
      * the current object.
      */
     $state[self::AUTHID] = $this->authId;
     /* What username we should force, if any. */
     if ($this->forcedUsername !== NULL) {
         /*
          * This is accessed by the login form, to determine if the user
          * is allowed to change the username.
          */
         $state['forcedUsername'] = $this->forcedUsername;
     }
     /* Save the $state-array, so that we can restore it after a redirect. */
     $id = SimpleSAML_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');
     $params = array('AuthState' => $id);
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
     /* The previous function never returns, so this code is never executed. */
     assert('FALSE');
 }
Example #24
0
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = (string) $_REQUEST['username'];
    $password = (string) $_REQUEST['password'];
    if (!isset($users[$username]) || $users[$username]['password'] !== $password) {
        $badUserPass = TRUE;
    } else {
        $user = $users[$username];
        if (!session_id()) {
            // session_start not called before. Do it here.
            session_start();
        }
        $_SESSION['uid'] = $user['uid'];
        $_SESSION['name'] = $user['name'];
        $_SESSION['mail'] = $user['mail'];
        $_SESSION['type'] = $user['type'];
        \SimpleSAML\Utils\HTTP::redirectTrustedURL($returnTo);
    }
}
/*
 * If we get this far, we need to show the login page to the user.
 */
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>exampleauth login page</title>
</head>
<body>
<h1>exampleauth login page</h1>
<p>In this example you can log in with two accounts: <code>student</code> and <code>admin</code>. In both cases, the password is the same as the username.</p>
Example #25
0
 public static function postLogout(SimpleSAML_IdP $idp, array $state)
 {
     $url = SimpleSAML\Module::getModuleURL('consent/logout_completed.php');
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
 }
Example #26
0
 /**
  * Handles a request to this discovery service.
  *
  * The IdP disco parameters should be set before calling this function.
  */
 public function handleRequest()
 {
     $this->start();
     // no choice made. Show discovery service page
     $idpList = $this->getIdPList();
     $idpList = $this->filterList($idpList);
     $preferredIdP = $this->getRecommendedIdP();
     $idpintersection = array_intersect(array_keys($idpList), $this->getScopedIDPList());
     if (sizeof($idpintersection) > 0) {
         $idpList = array_intersect_key($idpList, array_fill_keys($idpintersection, null));
     }
     $idpintersection = array_values($idpintersection);
     if (sizeof($idpintersection) == 1) {
         $this->log('Choice made [' . $idpintersection[0] . '] (Redirecting the user back. returnIDParam=' . $this->returnIdParam . ')');
         \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->returnURL, array($this->returnIdParam => $idpintersection[0]));
     }
     /*
      * Make use of an XHTML template to present the select IdP choice to the user. Currently the supported options
      * is either a drop down menu or a list view.
      */
     switch ($this->config->getString('idpdisco.layout', 'links')) {
         case 'dropdown':
             $templateFile = 'selectidp-dropdown.php';
             break;
         case 'links':
             $templateFile = 'selectidp-links.php';
             break;
         default:
             throw new Exception('Invalid value for the \'idpdisco.layout\' option.');
     }
     $t = new SimpleSAML_XHTML_Template($this->config, $templateFile, '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\Utils\HTTP::getSelfURLNoQuery());
     $t->data['rememberenabled'] = $this->config->getBoolean('idpdisco.enableremember', false);
     $t->show();
 }
Example #27
0
 /**
  * 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\Utils\HTTP::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;
     }
 }
Example #28
0
 /**
  * Helper function for sending CDC messages.
  *
  * @param string $to  The URL the message should be delivered to.
  * @param string $parameter  The query parameter the message should be sent in.
  * @param array $message  The CDC message.
  */
 private function send($to, $parameter, array $message)
 {
     assert('is_string($to)');
     assert('is_string($parameter)');
     $message['timestamp'] = time();
     $message = json_encode($message);
     $message = base64_encode($message);
     $signature = $this->calcSignature($message);
     $params = array($parameter => $message, 'Signature' => $signature);
     $url = \SimpleSAML\Utils\HTTP::addURLParameters($to, $params);
     if (strlen($url) < 2048) {
         \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
     } else {
         \SimpleSAML\Utils\HTTP::submitPOSTData($to, $params);
     }
 }
Example #29
0
 /**
  * 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\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 }
Example #30
0
 /**
  * Log out from this authentication source.
  *
  * This function should be overridden if the authentication source requires special
  * steps to complete a logout operation.
  *
  * If the logout process requires a redirect, the state should be saved. Once the
  * logout operation is completed, the state should be restored, and completeLogout
  * should be called with the state. If this operation can be completed without
  * showing the user a page, or redirecting, this function should return.
  *
  * @param array &$state  Information about the current logout operation.
  */
 public function logout(&$state)
 {
     assert('is_array($state)');
     $logoutUrl = $this->_casConfig['logout'];
     SimpleSAML_Auth_State::deleteState($state);
     // we want cas to log us out
     \SimpleSAML\Utils\HTTP::redirectTrustedURL($logoutUrl);
 }