The state must be an associative array. This class will add additional keys to this array. These keys will always start with 'SimpleSAML_Auth_State.'. It is also possible to add a restart URL to the state. If state information is lost, for example because it timed out, or the user loaded a bookmarked page, the loadState function will redirect to this URL. To use this, set $state[SimpleSAML_Auth_State::RESTART] to this URL. Both the saveState and the loadState function takes in a $stage parameter. This parameter is a security feature, and is used to prevent the user from taking a state saved one place and using it as input a different place. The $stage parameter must be a unique string. To maintain uniqueness, it must be on the form "." or ":". There is also support for passing exceptions through the state. By defining an exception handler when creating the state array, users of the state array can call throwException with the state and the exception. This exception will be passed to the handler defined by the EXCEPTION_HANDLER_URL or EXCEPTION_HANDLER_FUNC elements of the state array.
Author: Olav Morken, UNINETT AS.
Example #1
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;
     }
     $id = SimpleSAML_Auth_State::saveState($state, 'core:Logout-IFrame');
     $url = SimpleSAML_Module::getModuleURL('core/idp/logout-iframe.php', array('id' => $id));
     SimpleSAML_Utilities::redirect($url);
 }
Example #2
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));
 }
Example #3
0
 /**
  * Test the getPersistentAuthData() function.
  */
 public function testGetPersistentAuthData()
 {
     $mandatory = array('Attributes' => array(), 'Expire' => 1234, 'LogoutState' => 'logoutState', 'AuthInstant' => 123456, 'RememberMe' => true, 'saml:sp:NameID' => 'nameID');
     // check just mandatory parameters
     $state = $mandatory;
     $expected = $mandatory;
     $this->assertEquals($expected, SimpleSAML_Auth_State::getPersistentAuthData($state), 'Mandatory state attributes did not survive as expected' . print_r($expected, true));
     // check missing mandatory parameters
     unset($state['LogoutState']);
     unset($state['RememberMe']);
     $expected = $state;
     $this->assertEquals($expected, SimpleSAML_Auth_State::getPersistentAuthData($state), 'Some error occurred with missing mandatory parameters');
     // check additional non-persistent parameters
     $additional = array('additional1' => 1, 'additional2' => 2);
     $state = array_merge($mandatory, $additional);
     $expected = $mandatory;
     $this->assertEquals($expected, SimpleSAML_Auth_State::getPersistentAuthData($state), 'Additional parameters survived');
     // check additional persistent parameters
     $additional['PersistentAuthData'] = array('additional1');
     $state = array_merge($mandatory, $additional);
     $expected = $state;
     unset($expected['additional2']);
     unset($expected['PersistentAuthData']);
     $this->assertEquals($expected, SimpleSAML_Auth_State::getPersistentAuthData($state), 'Some error occurred with additional, persistent parameters');
     // check only additional persistent parameters
     $state = $additional;
     $expected = $state;
     unset($expected['additional2']);
     unset($expected['PersistentAuthData']);
     $this->assertEquals($expected, SimpleSAML_Auth_State::getPersistentAuthData($state), 'Some error occurred with additional, persistent parameters, and no mandatory ones');
 }
Example #4
0
 /**
  * Start authentication.
  *
  * This function never returns.
  *
  * @param string $authId  The identifier of the authentication source.
  * @param string|array $return The URL or function we should direct the
  * user to after authentication. If using a URL obtained from user input,
  * please make sure to check it by calling
  * SimpleSAML_Utilities::checkURLAllowed().
  * @param string|NULL $errorURL The URL we should direct the user to after
  * failed authentication. Can be NULL, in which case a standard error page
  * will be shown. If using a URL obtained from user input, please make sure
  * to check it by calling SimpleSAML_Utilities::checkURLAllowed().
  * @param array $params Extra information about the login. Different
  * authentication requestors may provide different information. Optional,
  * will default to an empty array.
  */
 public static function initLogin($authId, $return, $errorURL = NULL, array $params = array())
 {
     assert('is_string($authId)');
     assert('is_string($return) || is_array($return)');
     assert('is_string($errorURL) || is_null($errorURL)');
     $state = array_merge($params, array('SimpleSAML_Auth_Default.id' => $authId, 'SimpleSAML_Auth_Default.Return' => $return, 'SimpleSAML_Auth_Default.ErrorURL' => $errorURL, 'LoginCompletedHandler' => array(get_class(), 'loginCompleted'), 'LogoutCallback' => array(get_class(), 'logoutCallback'), 'LogoutCallbackState' => array('SimpleSAML_Auth_Default.logoutSource' => $authId)));
     if (is_string($return)) {
         $state['SimpleSAML_Auth_Default.ReturnURL'] = $return;
     }
     if ($errorURL !== NULL) {
         $state[SimpleSAML_Auth_State::EXCEPTION_HANDLER_URL] = $errorURL;
     }
     $as = SimpleSAML_Auth_Source::getById($authId);
     if ($as === NULL) {
         throw new Exception('Invalid authentication source: ' . $authId);
     }
     try {
         $as->authenticate($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);
     }
     self::loginCompleted($state);
 }
Example #5
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)');
     $session = SimpleSAML_Session::getSessionFromRequest();
     // Register a logout handler so we can later log ourselves out when needed.
     // @todo, this doesn't work; simplesamlphp mailinglist has been notified
     $session->registerLogoutHandler('sspmod_authTiqr_Auth_Process_Tiqr', 'logout');
     $sessionId = $session->getSessionId();
     $server = sspmod_authTiqr_Auth_Tiqr::getServer(false);
     $user = $server->getAuthenticatedUser($sessionId);
     if (!empty($user)) {
         // User is already authenticated
         return;
     }
     /* User interaction nessesary. Throw exception on isPassive request */
     if (isset($state['isPassive']) && $state['isPassive'] == TRUE) {
         throw new SimpleSAML_Error_NoPassive('Unable to perform mobile authentication on passive request.');
     }
     if (!isset($state["Attributes"][$this->_uidAttribute])) {
         throw new SimpleSAML_Error_Exception('No user id present, is first factor authentication properly set up?');
     }
     $userId = $state["Attributes"][$this->_uidAttribute][0];
     $displayName = $state["Attributes"][$this->_cnAttribute][0];
     $state["tiqrUser"] = array("userId" => $userId, "displayName" => $displayName);
     /* Save state and redirect. */
     $id = SimpleSAML_Auth_State::saveState($state, sspmod_authTiqr_Auth_Tiqr::STAGEID);
     $url = SimpleSAML_Module::getModuleURL('authTiqr/login.php');
     SimpleSAML_Utilities::redirect($url, array('AuthState' => $id));
 }
Example #6
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);
 }
Example #7
0
 /**
  * Log-in using Facebook cronus
  *
  * @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('facebook auth state id = ' . $stateID);
     $facebook = new Facebook($this->api_key, $this->secret);
     $u = $facebook->require_login(SimpleSAML_Module::getModuleUrl('authfacebook') . '/linkback.php?next=' . $stateID);
     # http://developers.facebook.com/documentation.php?v=1.0&method=users.getInfo
     /* Causes an notice / warning...
     		if ($facebook->api_client->error_code) {
     			throw new Exception('Unable to load profile from facebook');
     		}
     		*/
     // http://developers.facebook.com/docs/reference/rest/users.getInfo
     $info = $facebook->api_client->users_getInfo($u, array('uid', 'first_name', 'middle_name', 'last_name', 'name', 'locale', 'current_location', 'affiliations', 'pic_square', 'profile_url', 'sex', 'email', 'pic', 'username', 'about_me', 'status', 'profile_blurb'));
     $attributes = array();
     foreach ($info[0] as $key => $value) {
         if (is_string($value) && !empty($value)) {
             $attributes['facebook.' . $key] = array((string) $value);
         }
     }
     if (array_key_exists('username', $info[0])) {
         $attributes['facebook_user'] = array($info[0]['username'] . '@facebook.com');
     } else {
         $attributes['facebook_user'] = array($u . '@facebook.com');
     }
     $attributes['facebook_targetedID'] = array('http://facebook.com!' . $u);
     $attributes['facebook_cn'] = array($info[0]['name']);
     SimpleSAML_Logger::debug('Facebook Returned Attributes: ' . implode(", ", array_keys($attributes)));
     $state['Attributes'] = $attributes;
 }
Example #8
0
 /**
  * Apply filter to validate attributes.
  *
  * @param array &$request  The current request
  */
 public function process(&$request)
 {
     $authorize = FALSE;
     assert('is_array($request)');
     assert('array_key_exists("Attributes", $request)');
     $attributes =& $request['Attributes'];
     foreach ($this->valid_attribute_values as $name => $patterns) {
         if (array_key_exists($name, $attributes)) {
             foreach ($patterns as $pattern) {
                 $values = $attributes[$name];
                 if (!is_array($values)) {
                     $values = array($values);
                 }
                 foreach ($values as $value) {
                     if (preg_match($pattern, $value)) {
                         $authorize = TRUE;
                         break 3;
                     }
                 }
             }
         }
     }
     if (!$authorize) {
         /* 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::redirect($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));
 }
 /**
  * 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));
 }
Example #11
0
 /**
  * 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);
 }
Example #12
0
 public function finalStep(&$state)
 {
     assert('is_array($state)');
     $stateID = SimpleSAML_Auth_State::getStateId($state);
     SimpleSAML_Logger::debug("oauth wrap:  Using this verification code [" . $state['authwindowslive:wrap_verification_code'] . "]");
     // Retrieve Access Token
     // Documentation at:  http://msdn.microsoft.com/en-us/library/live/hh243641
     // http://msdn.microsoft.com/en-us/library/live/hh243647.aspx
     $auth_code = $state['authwindowslive:wrap_verification_code'];
     $redirect_uri = SimpleSAML_Module::getModuleUrl('authwindowslive') . '/linkback.php?wrap_client_state=' . urlencode($stateID);
     $fields = array('code' => urlencode($auth_code), 'client_id' => urlencode($this->key), 'client_secret' => urlencode($this->secret), 'redirect_uri' => urlencode($redirect_uri), 'grant_type' => urlencode('authorization_code'));
     $post = '';
     foreach ($fields as $key => $value) {
         $post .= $key . '=' . $value . '&';
     }
     $post = rtrim($post, '&');
     $curl = curl_init();
     curl_setopt($curl, CURLOPT_URL, 'https://login.live.com/oauth20_token.srf');
     curl_setopt($curl, CURLOPT_POST, 5);
     curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
     $result = curl_exec($curl);
     curl_close($curl);
     $response = json_decode($result);
     $accesstoken = $response->access_token;
     SimpleSAML_Logger::debug('LIVE AccessToken: ' . $accesstoken);
     // $url = 'https://apis.live.net/v5.0/me/contacts?access_token='.$accesstoken.'';
     $url = 'https://apis.live.net/v5.0/me?access_token=' . $accesstoken . '';
     $xmlresponse = $this->curl_file_get_contents($url);
     SimpleSAML_Logger::debug('LIVE Response: ' . $xmlresponse);
     $xml = json_decode($xmlresponse, true);
     foreach ($xml as $key => $value) {
         SimpleSAML_Logger::debug('LIVE ' . $key . ':' . $value);
     }
     $attributes = array();
     $attributes['windowslive_uid'] = array($xml['id']);
     //$attributes['uid']=$attributes['windowslive_uid'];
     $attributes['windowslive_name'] = array($xml['name']);
     //$attributes['cn']=$attributes['windowslive_name'];
     $attributes['windowslive_first_name'] = array($xml['first_name']);
     //$attributes['givenName']=$attributes['windowslive_first_name'];
     $attributes['windowslive_last_name'] = array($xml['last_name']);
     //$attributes['sn']=$attributes['windowslive_last_name'];
     //$attributes['windowslive_link'] = array($xml['link']);
     $attributes['windowslive_email'] = array($xml['emails']['account']);
     //$attributes['mail']=$attributes['windowslive_email'];
     /*$attributes['windowslive_birth_month'] = array($xml['birth_month']);
     		$attributes['windowslive_gender'] = array($xml['gender']);
     		$attributes['windowslive_city'] = array($xml['addresses']['personal']['city']);
     		$attributes['windowslive_state'] = array($xml['addresses']['personal']['state']);
     		$attributes['windowslive_region'] = array($xml['addresses']['personal']['region']);
     		$attributes['windowslive_locale'] = array($xml['locale']);*/
     //$attributes['language']=$attributes['windowslive_locale'];
     //$attributes['windowslive_updated_time'] = array($xml['updated_time']);
     $attributes['windowslive_user'] = array($xml['id'] . '@live.com');
     $state['Attributes'] = $attributes;
 }
 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('authtfaga/login.php');
     SimpleSAML_Utilities::redirect($url, array('AuthState' => $id));
 }
Example #14
0
 /**
  * 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));
 }
Example #15
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 #16
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 #17
0
 /**
  * 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::redirect($as_url);
     } catch (Exception $e) {
         // attach the exception to the state
         SimpleSAML_Auth_State::throwException($state, $e);
     }
 }
Example #18
0
 /**
  * Redirect to page setting CDC.
  *
  * @param array &$state  The request state.
  */
 public function process(&$state)
 {
     assert('is_array($state)');
     if (!isset($state['Source']['entityid'])) {
         SimpleSAML_Logger::warning('saml:CDC: Could not find IdP entityID.');
         return;
     }
     /* Save state and build request. */
     $id = SimpleSAML_Auth_State::saveState($state, 'cdc:resume');
     $returnTo = SimpleSAML_Module::getModuleURL('cdc/resume.php', array('domain' => $this->domain));
     $params = array('id' => $id, 'entityID' => $state['Source']['entityid']);
     $this->client->sendRequest($returnTo, 'append', $params);
 }
Example #19
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_Utilities::redirect($url);
 }
Example #20
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);
 }
Example #21
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';
     }
 }
 /**
  * Log-in using MySpace 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;
     $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
     // Get the request token
     $requestToken = $consumer->getRequestToken('http://api.myspace.com/request_token');
     SimpleSAML_Logger::debug("Got a request token from the OAuth service provider [" . $requestToken->key . "] with the secret [" . $requestToken->secret . "]");
     $state['authmyspace:requestToken'] = $requestToken;
     $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT);
     SimpleSAML_Logger::debug('authmyspace auth state id = ' . $stateID);
     // Authorize the request token
     $consumer->getAuthorizeRequest('http://api.myspace.com/authorize', $requestToken, TRUE, SimpleSAML_Module::getModuleUrl('authmyspace') . '/linkback.php?stateid=' . $stateID);
 }
Example #23
0
 /**
  * Log-in using Twitter 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);
     $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
     // Get the request token
     $linkback = SimpleSAML_Module::getModuleURL('authtwitter/linkback.php', array('AuthState' => $stateID));
     $requestToken = $consumer->getRequestToken('https://api.twitter.com/oauth/request_token', array('oauth_callback' => $linkback));
     SimpleSAML_Logger::debug("Got a request token from the OAuth service provider [" . $requestToken->key . "] with the secret [" . $requestToken->secret . "]");
     $state['authtwitter:authdata:requestToken'] = $requestToken;
     SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT);
     // Authorize the request token
     $consumer->getAuthorizeRequest('https://api.twitter.com/oauth/authenticate', $requestToken);
 }
Example #24
0
 /**
  * Log-in using Bnet OAuth2.0 API
  *
  * @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);
     $this->state = $state;
     $this->stateID = $stateID;
     // Without scopes you will get access to a users account ID and BattleTag.
     //$scopes = 'wow.profile sc2.profile';
     // Authenticate the user
     // https://dev.battle.net/docs/read/oauth
     $authorizeURL = 'https://eu.battle.net/oauth/authorize?' . 'client_id=' . urlencode($this->key) . '&redirect_uri=' . urlencode($this->linkback) . '&response_type=code' . '&access_type=online' . '&state=' . urlencode($stateID);
     $session = SimpleSAML_Session::getInstance();
     $session->setData('string', 'authStateId', $stateID);
     SimpleSAML_Utilities::redirectTrustedURL($authorizeURL);
 }
Example #25
0
	/**
	 * Called by linkback, to finish validate/ finish logging in.
	 * @param state $state
	 * @return list username, casattributes/ldap attributes
	 */
	public function finalStep(&$state) {
global $mysqli;
		$ticket = $state['cas:ticket'];
		$stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT);
		$service =  SimpleSAML_Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID));
		list($username, $casattributes) = $this->casValidation($ticket, $service);

		//recherche du login gepi
		$path = dirname(dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))));
		require_once($path."/secure/connect.inc.php");
		// Database connection
		require_once($path."/lib/mysql.inc");
		
		if ($this->_champ_cas_uid_retour == 'username') {
			$uid = $username;
		} else {
			$uid = $casattributes['uid'];
		}

		$requete = 'SELECT '.$this->_search_table_gepi_login_column.' FROM '.$this->_search_table_name.' WHERE '.$this->_search_table_cas_uid_column.'=\''.$uid.'\'';
		$result = $mysqli->query($requete);
		
		$valeur = $result->fetch_array(MYSQLI_NUM);
		if (!$valeur) {
			//utilisateur non trouvé dans la base gepi, l'authentification a échoué
				SimpleSAML_Logger::error('gepicas:' . $this->authId .
					': not authenticated. User is in the CAS but not in the gepi local database.');
				throw new SimpleSAML_Error_UserNotFound('Utilisateur non trouve dans la base locale');			
		}
		$attributes['login'] = array($valeur[0]);
		$attributes['login_gepi'] = array($valeur[0]);
		
		# On interroge la base de données pour récupérer des attributs qu'on va retourner
		# Cela ne sert pas à gepi directement mais à des services qui peuvent s'appuyer sur gepi pour l'athentification
		$query = $mysqli->query("SELECT nom, prenom, email, statut FROM utilisateurs WHERE (login = '******'login_gepi'][0]."')");
		$row = $query->fetch_object();
		
		$attributes['nom'] = array($row->nom);
		$attributes['prenom'] = array($row->prenom);
		$attributes['statut'] = array($row->statut);
		$attributes['email'] = array($row->email);
		
		$state['Attributes'] = $attributes;
		
		SimpleSAML_Auth_Source::completeAuth($state);
	}
Example #26
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"));
}
Example #27
0
 /**
  * Log-in using LinkedIn platform
  * Documentation at: http://developer.linkedin.com/docs/DOC-1008
  *
  * @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::getStateId($state);
     SimpleSAML\Logger::debug('authlinkedin auth state id = ' . $stateID);
     $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
     // Get the request token
     $requestToken = $consumer->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken', array('oauth_callback' => SimpleSAML\Module::getModuleUrl('authlinkedin') . '/linkback.php?stateid=' . $stateID));
     SimpleSAML\Logger::debug("Got a request token from the OAuth service provider [" . $requestToken->key . "] with the secret [" . $requestToken->secret . "]");
     $state['authlinkedin:requestToken'] = $requestToken;
     // Update the state
     SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT);
     // Authorize the request token
     $consumer->getAuthorizeRequest('https://www.linkedin.com/uas/oauth/authenticate', $requestToken);
 }
Example #28
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);
     // SimpleSAML_Logger::debug('facebook auth state id = ' . $stateID);
     $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
     // Get the request token
     $requestToken = $consumer->getRequestToken('http://twitter.com/oauth/request_token');
     SimpleSAML_Logger::debug("Got a request token from the OAuth service provider [" . $requestToken->key . "] with the secret [" . $requestToken->secret . "]");
     $oauthState = array('requestToken' => serialize($requestToken), 'stateid' => $stateID);
     $session = SimpleSAML_Session::getInstance();
     $session->setData('oauth', 'oauth', $oauthState);
     // Authorize the request token
     $consumer->getAuthorizeRequest('http://twitter.com/oauth/authenticate', $requestToken);
 }
 /**
  * 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);
 }
Example #30
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);
     SimpleSAML_Logger::debug('facebook auth state id = ' . $stateID);
     $facebook = new Facebook($this->api_key, $this->secret);
     $u = $facebook->require_login($stateID);
     # http://developers.facebook.com/documentation.php?v=1.0&method=users.getInfo
     /* Causes an notice / warning...
     		if ($facebook->api_client->error_code) {
     			throw new Exception('Unable to load profile from facebook');
     		}
     		*/
     $info = $facebook->api_client->users_getInfo($u, array('first_name', 'last_name'));
     $fullname = $info[0]['first_name'] . ' ' . $info[0]['last_name'];
     $attributes = array('sn' => array($info[0]['last_name']), 'givenName' => array($info[0]['first_name']), 'cn' => array($info[0]['first_name'] . ' ' . $info[0]['last_name']), 'uid' => array($u), 'eduPersonPrincipalName' => array('facebook:' . $u));
     $state['Attributes'] = $attributes;
 }