This function checks if the user is authenticated with the default authentication source selected by the
'default-authsource' option in 'config.php'.
public isAuthenticated ( ) : boolean | ||
return | boolean | True if the user is authenticated, false if not. |
public function __construct() { // Obligatoire parent::__construct(); $this->data = array(); // System FED Oxylane if (FEDACTIVE) { require __DIR__ . '/../simplesaml/lib/_autoload.php'; $as = new SimpleSAML_Auth_Simple('Oxylane-sp'); $isAuth = $as->isAuthenticated(); if (!$isAuth) { $as->requireAuth(); } else { $attributes = $as->getAttributes(); $this->data['fed']['0'] = $attributes['uid'][0]; //identifiant $this->data['fed']['1'] = $attributes['cn'][0]; //nom de la personne $this->data['fed']['2'] = $attributes['mail'][0]; //mail de la personne } } else { $this->data['fed']['0'] = "ID"; $this->data['fed']['1'] = "NOM"; $this->data['fed']['2'] = "MAIL"; } // END FED // Chargement des ressources pour tout le contrôleur $this->load->database(); $this->load->helper('form'); $this->load->helper('titreUrl'); $this->load->helper('convertlien'); $this->load->library('form_validation'); $this->load->model('pages_model', 'pm'); $this->load->model('plannings_model', 'plm'); $this->load->model('types_model', 'tm'); $this->load->model('chaines_model', 'cm'); $this->load->model('groupes_model', 'gm'); $this->load->model('bandeau_model', 'bm'); if (FEDLOG) { $this->load->model('logs_model', 'lm'); } // Récupération de toute les chaines $this->data['chaines'] = $this->cm->getAll(); $this->data['superadmin'] = true; // Cette méthode permet de changer les délimiteurs par défaut des messages d'erreur (<p></p>). $this->form_validation->set_error_delimiters('<p class="alert alert-error fade in"><a class="close" data-dismiss="alert" href="#">×</a>', '</p>'); }
public function executeSignin($request) { $user = $this->getUser(); if ($user->isAuthenticated()) { return $this->redirect('@homepage'); } // Create SimpleSAML module $simpleSAMLAuth = new SimpleSAML_Auth_Simple('default-sp'); // If the user is authenticated from the IdP if ($simpleSAMLAuth->isAuthenticated()) { $attributes = $simpleSAMLAuth->getAttributes(); // save the referer $user_referer = $user->getReferer($request->getReferer()); // Try to find the user with his uid $query = Doctrine_Core::getTable('sfGuardUser')->createQuery('u')->where('u.username = ?', $attributes['eduPersonPrincipalName'][0]); // If the sGuardUser already exists in the database, it's OK if ($query->count() >= 1) { $guard_user = $query->fetchOne(); $guard_user->setEmailAddress($attributes['mail'][0]); $guard_user->setLastName($attributes['cn'][0]); $guard_user->save(); } else { // the user doesn't exist, we create a new one with random password $guard_user = new sfGuardUser(); $guard_user->setUsername($attributes['eduPersonPrincipalName'][0]); $guard_user->setPassword(md5(microtime() . $attributes['eduPersonPrincipalName'][0] . mt_rand())); $guard_user->setEmailAddress($attributes['mail'][0]); $guard_user->setLastName($attributes['cn'][0]); $guard_user->setIsActive(true); $guard_user->save(); } // Let the User signin // The auth is not rembered : the IdP can decide that $this->getUser()->signin($guard_user, $remember = false); // always redirect to a URL set in app.yml // or to the referer // or to the homepage $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user_referer); return $this->redirect('' != $signinUrl ? $signinUrl : '@homepage'); } else { if ($request->isXmlHttpRequest()) { $this->getResponse()->setHeaderOnly(true); $this->getResponse()->setStatusCode(401); return sfView::NONE; } // if we have been forwarded, then the referer is the current URL // if not, this is the referer of the current request $user->setReferer($this->getContext()->getActionStack()->getSize() > 1 ? $request->getUri() : $request->getReferer()); /* gyufi $this->url_idp = $simpleSAMLAuth->login(array( //'saml:idp' => 'https://openidp.feide.no', 'saml:idp' => 'https://aai.sztaki.hu/idp-partners', 'saml:idp' => 'https://aai.sztaki.hu/idp', )); */ $this->url_idp = $simpleSAMLAuth->login(); // Nothing happened after there, $simpleSAMLAuth->login() calls exit() /* $module = sfConfig::get('sf_login_module'); if ($this->getModuleName() != $module) { return $this->redirect($module.'/'.sfConfig::get('sf_login_action')); } $this->getResponse()->setStatusCode(401); */ } }
function get_attributes() { // Only run in step 5 or later ! So change when steps array is changed! if (isset($_REQUEST['s'])) { if ($_REQUEST['s'] >= 4) { if ($ssp_location = issetweb('ssp_location')) { $ssp_autoloader = $ssp_location . '/lib/_autoload.php'; if (is_readable($ssp_autoloader)) { //echo "<pre>sesion:"; var_dump($_SESSION); echo "rquest"; var_dump($_REQUEST); include_once $ssp_autoloader; if ($ssp_authsource = issetweb('ssp_authsource')) { $as = new SimpleSAML_Auth_Simple($ssp_authsource); if (!$as->isAuthenticated()) { $as->requireAuth(); } $attributes = $as->getAttributes(); foreach (array_keys($attributes) as $at) { // These are key|value pairs to populate the SELECT boxes $simpleattrs[$at] = $at . " (" . $attributes[$at][0] . ")"; } // Add attributes themselves as well, for later use $simpleattrs['saml'] = $attributes; // echo "<pre>"; var_dump($simpleattrs); ksort($simpleattrs); return $simpleattrs; } } } } } return false; }
public function beforeProcess(&$action) { if (CopixConfig::get('conf_Saml_actif') != 1) { return; } require_once COPIX_UTILS_PATH . '../../simplesamlphp/lib/_autoload.php'; $asId = 'iconito-sql'; if (CopixConfig::exists('default|conf_Saml_authSource') && CopixConfig::get('default|conf_Saml_authSource')) { $asId = CopixConfig::get('default|conf_Saml_authSource'); } $as = new SimpleSAML_Auth_Simple($asId); $ppo->user = _currentUser(); if ($as->isAuthenticated() && !$ppo->user->isConnected()) { $attributes = $as->getAttributes(); $uidAttribute = 'login_dbuser'; if (CopixConfig::exists('default|conf_Saml_uidAttribute') && CopixConfig::get('default|conf_Saml_uidAttribute')) { $uidAttribute = CopixConfig::get('default|conf_Saml_uidAttribute'); } $ppo->saml_user = null; if (isset($attributes[$uidAttribute]) && isset($attributes[$uidAttribute][0])) { $ppo->saml_user = $attributes[$uidAttribute][0]; } if ($ppo->saml_user) { $ppo->iconito_user = Kernel::getUserInfo("LOGIN", $ppo->saml_user); if ($ppo->iconito_user['login']) { _currentUser()->login(array('login' => $ppo->iconito_user['login'], 'assistance' => true)); $url_return = CopixUrl::get('kernel||doSelectHome'); // $url_return = CopixUrl::get ('assistance||users'); return new CopixActionReturn(COPIX_AR_REDIRECT, $url_return); } else { $ppo->cas_error = 'no-iconito-user'; return _arPpo($ppo, 'cas.tpl'); } } } if (!$as->isAuthenticated() && $ppo->user->isConnected()) { $ppo->user = _currentUser(); if ($ppo->user->isConnected()) { CopixAuth::getCurrentUser()->logout(array()); CopixEventNotifier::notify('logout', array('login' => CopixAuth::getCurrentUser()->getLogin())); CopixAuth::destroyCurrentUser(); CopixSession::destroyNamespace('default'); } } }
public static function checkLoggedAndSameAuth() { $session = SimpleSAML_Session::getSessionFromRequest(); $uregconf = SimpleSAML_Configuration::getConfig('module_selfregister.php'); $asId = $uregconf->getString('auth'); $as = new SimpleSAML_Auth_Simple($asId); if ($as->isAuthenticated()) { return $as; } return false; }
public function logout() { //check for application session and invalidate if (Auth::check()) { Auth::logout(); } //check for sso session and invalidate $as = new \SimpleSAML_Auth_Simple('default-sp'); if ($as->isAuthenticated()) { $as->logout(); } //redirect to home return Redirect::Action('mainController@index'); }
public function authenticate() { try { $as = new \SimpleSAML_Auth_Simple($this->_domain); $globalConfig = \SimpleSAML_Configuration::getInstance(); //$globalConfig::setConfigDir(G_CONFIGDIR.'saml/'); $as->requireAuth(); if ($as->isAuthenticated()) { $attributes = $as->getAttributes(); if (!array_key_exists($this->_sso_settings['saml_email'], $attributes)) { // TemplateController::setMessage(("A valid email is needed for account related communication").". ".("Check that the %s attribute (%s) defined in your configuration is correct",("Email"),$this->_sso_settings['saml_email']), 'error'); $this->ssoLogout(); } elseif (!array_key_exists($this->_sso_settings['saml_first_name'], $attributes)) { // TemplateController::setMessage(("'%s' is required",("First name")).". ".("Check that the %s attribute (%s) defined in your configuration is correct",("First name"),$this->_sso_settings['saml_first_name']), 'error'); $this->ssoLogout(); } elseif (!array_key_exists($this->_sso_settings['saml_last_name'], $attributes)) { // TemplateController::setMessage(("'%s' is required",("Last name")).". ".("Check that the %s attribute (%s) defined in your configuration is correct",("Last name"),$this->_sso_settings['saml_last_name']), 'error'); $this->ssoLogout(); } else { if (trim($attributes[$this->_sso_settings['saml_email']][0]) == '') { $attributes[$this->_sso_settings['saml_email']][0] = " "; // TemplateController::setMessage(("A valid email is needed for account related communication"), 'error'); } if (trim($attributes[$this->_sso_settings['saml_first_name']][0]) == '' && trim($attributes[$this->_sso_settings['saml_last_name']][0]) == '') { $attributes[$this->_sso_settings['saml_first_name']][0] = ' '; $attributes[$this->_sso_settings['saml_last_name']][0] = ' '; } else { if (trim($attributes[$this->_sso_settings['saml_first_name']][0]) == '') { $attributes[$this->_sso_settings['saml_first_name']][0] = $attributes[$this->_sso_settings['saml_last_name']][0]; } if (trim($attributes[$this->_sso_settings['saml_last_name']][0]) == '') { $attributes[$this->_sso_settings['saml_last_name']][0] = $attributes[$this->_sso_settings['saml_first_name']][0]; } } $this->_login($attributes); //pr($attributes);exit; //echo "redirect now";exit; //\SimpleSAML_Utilities::postRedirect("https://index.php", $attributes); } } } catch (\SimpleSAML_Error_Error $e) { $this->_samlErrorHandler($e); } catch (\Exception $e) { handleNormalFlowExceptions($e); } return $this; }
public function __construct() { // Obligatoire parent::__construct(); $this->data = array(); // System FED Oxylane if (FEDACTIVE) { require __DIR__ . '/../simplesaml/lib/_autoload.php'; $as = new SimpleSAML_Auth_Simple('Oxylane-sp'); $isAuth = $as->isAuthenticated(); $url = $as->getLoginURL(); if (!$isAuth) { //$url = $as->getLoginURL(); //echo '<p>You are not authenticated. <a href="' . htmlspecialchars($url) . '">Log in</a>.</p>'; $as->requireAuth(); } else { //$url = $as->getLogoutURL(); //echo '<p>You are currently authenticated. <a href="' . htmlspecialchars($url) . '">Log out</a>.</p>'; $attributes = $as->getAttributes(); $uid = $attributes['uid'][0]; $this->data['fed']['0'] = $uid; $this->data['fed']['1'] = $attributes['cn'][0]; $this->data['fed']['2'] = $attributes['mail'][0]; $this->load->model('admins_model', 'am'); $admins = $this->am->getAll(); if (!$this->in_array_column($uid, $admins)) { echo "Utilisateur non autorisés"; redirect('welcome', 'refresh'); } } } else { $this->data['fed']['0'] = "ID"; $this->data['fed']['1'] = "NOM"; $this->data['fed']['2'] = "MAIL"; } // END System FED Oxylane // Chargement des ressources pour tout le contrôleur $this->load->database(); $this->load->helper('form'); $this->load->library('form_validation'); $this->load->model('pages_model', 'pm'); $this->load->model('chaines_model', 'cm'); $this->load->model('groupes_model', 'gm'); $this->load->model('logs_model', 'lm'); }
public static function isAuthenticated() { require_once SamlAuth::LIB_AUTOLOAD; $source = null; $config = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($config, 'core:authsource_list.tpl.php'); $t->data['sources'] = SimpleSAML_Auth_Source::getSourcesMatch('-sp'); foreach ($t->data['sources'] as &$_source) { $as = new SimpleSAML_Auth_Simple($_source); if ($as->isAuthenticated()) { $source = $as; break; } } if ($source === null) { return false; } return $source; }
public function authenticate(TokenInterface $token) { /** @var string $authenticationType */ $authenticationType = $this->config->getValue('auth', 'login-admin'); if (php_sapi_name() === 'cli') { return $this->getTokenForUsername($authenticationType); } $as = new \SimpleSAML_Auth_Simple($authenticationType); if (!$as->isAuthenticated()) { throw new AuthenticationException("Authsource '{$authenticationType}' is invalid"); } /** @var string $userIdAttributeName */ $userIdAttributeName = $this->config->getValue('useridattr', 'eduPersonPrincipalName'); // Check if userid exists $attributes = $as->getAttributes(); if (!isset($attributes[$userIdAttributeName])) { throw new AuthenticationException("Attribute '{$userIdAttributeName}' with User ID is missing."); } return $this->getTokenForUsername($attributes[$userIdAttributeName][0]); }
function mostrarBotonLogin() { //configuración de simplesaml para autenticación SSO (single sign ON) $saml_lib_path = '/var/simplesamlphp/lib/_autoload.php'; require_once $saml_lib_path; $aplication_base_url = $this->host . $this->site; $source = 'SP_SNIES'; # Fuente de autenticación definida en el authsources del SP $as = new SimpleSAML_Auth_Simple($source); # Se pasa como parametro la fuente de autenticación //var_dump($as->isAuthenticated()); if (!$as->isAuthenticated()) { $this->formulario(); } else { //$valorCodificado = "action=loginSso"; $valorCodificado = "&pagina=listadoVariablesSnies"; //$esteBloque=$this->miConfigurador->getVariableConfiguracion ( 'esteBloque' ); //$valorCodificado .= "&bloque=" . $esteBloque ['nombre']; //$valorCodificado .= "&bloqueGrupo=" . $esteBloque ["grupo"]; $valorCodificado = $this->miConfigurador->fabricaConexiones->crypto->codificar($valorCodificado); //Mostrar enlace //Rescatar el parámetro enlace desde los datos de configuraión en la base de datos $variable = $this->miConfigurador->getVariableConfiguracion("enlace"); $miEnlace = $this->host . $this->site . '/index.php?' . $variable . '=' . $valorCodificado; header("Location: " . $miEnlace); //var_dump($miEnlace); $attributes = $as->getAttributes(); if (empty($attributes)) { echo 'No se obtuvieron atributos del usuario'; } else { echo '<table class="table table-bordered table-striped">'; foreach ($attributes as $key => $values) { echo '<tr><td>' . $key . '</td><td>'; echo implode('<br>', $values); echo '</td></tr>'; } echo '</table>'; } //echo '<p><a class="btn" href="logout.php">Cerrar sesión</a></p>'; } }
/** * Process a request. * * This function never returns. * * @param Auth_OpenID_Request $request The request we are processing. */ public function processRequest(array $state) { assert('isset($state["request"])'); SimpleSAML_Utilities::maskErrors(E_NOTICE | E_STRICT); $request = $state['request']; if (!$this->authSource->isAuthenticated()) { if ($request->immediate) { /* Not logged in, and we cannot show a login form. */ $this->sendResponse($request->answer(FALSE)); } $resumeURL = $this->getStateURL('resume.php', $state); $this->authSource->requireAuth(array('ReturnTo' => $resumeURL)); } $identity = $this->getIdentity(); assert('$identity !== FALSE'); /* Should always be logged in here. */ if (!$request->idSelect() && $identity !== $request->identity) { /* The identity in the request doesn't match the one of the logged in user. */ throw new SimpleSAML_Error_Exception('Logged in as different user than the one requested.'); } if ($this->isTrusted($identity, $request->trust_root)) { $trusted = TRUE; } elseif (isset($state['TrustResponse'])) { $trusted = (bool) $state['TrustResponse']; } else { if ($request->immediate) { /* Not trusted, and we cannot show a trust-form. */ $this->sendResponse($request->answer(FALSE)); } $trustURL = $this->getStateURL('trust.php', $state); SimpleSAML_Utilities::redirect($trustURL); } if (!$trusted) { /* The user doesn't trust this site. */ $this->sendResponse($request->answer(FALSE)); } /* The user is authenticated, and trusts this site. */ $this->sendResponse($request->answer(TRUE, NULL, $identity)); }
/** * Executes this filter. * * @param sfFilterChain $filterChain A sfFilterChain instance */ public function execute($filterChain) { // disable security on login and secure actions /* if ( (sfConfig::get('sf_login_module') == $this->context->getModuleName()) && (sfConfig::get('sf_login_action') == $this->context->getActionName()) || (sfConfig::get('sf_secure_module') == $this->context->getModuleName()) && (sfConfig::get('sf_secure_action') == $this->context->getActionName()) ) { $filterChain->execute(); return; } */ if ($this->context->getUser()->isAuthenticated()) { $as = new SimpleSAML_Auth_Simple('default-sp'); if (!$as->isAuthenticated()) { $this->context->getUser()->setAuthenticated(FALSE); } } // the user has access, continue $filterChain->execute(); }
/** * Is the current user authenticated? * * @return bool TRUE if the user is authenticated, FALSE if not. */ public function isAuthenticated() { return $this->authSource->isAuthenticated(); }
* @author Jacob Christiansen <*****@*****.**> * @copyright 2009 Jacob Christiansen * @license http://www.opensource.org/licenses/mit-license.php MIT License * @link http://github.com/janus-ssp/janus/ * @since File available since Release 1.5.1 */ require __DIR__ . '/_includes.php'; // Initial setup $config = SimpleSAML_Configuration::getInstance(); $janus_config = sspmod_janus_DiContainer::getInstance()->getConfig(); $authsource = $janus_config->getValue('auth', 'login-admin'); $useridattr = $janus_config->getValue('useridattr', 'eduPersonPrincipalName'); $et = new SimpleSAML_XHTML_Template($config, 'janus:editentity.php', 'janus:editentity'); $as = new SimpleSAML_Auth_Simple($authsource); // Validate user if ($as->isAuthenticated()) { $attributes = $as->getAttributes(); // Check if userid exists if (!isset($attributes[$useridattr])) { throw new Exception('User ID is missing'); } $userid = $attributes[$useridattr][0]; } else { echo $et->t('error_no_access'); exit; } // Get Entity controller $mcontroller = sspmod_janus_DiContainer::getInstance()->getEntityController(); // Get the user $user = new sspmod_janus_User(); $user->setUserid($userid);
$title = 'SimpleSAMLphp Example SAML SP'; $user_session_key = 'user_session'; $saml_sso = 'saml_sso'; // If the user is logged in and requesting a logout. if (isset($_SESSION[$user_session_key]) && isset($_REQUEST['logout'])) { $sp = $_SESSION[$user_session_key]['sp']; unset($_SESSION[$user_session_key]); $as = new SimpleSAML_Auth_Simple($sp); $as->logout(["ReturnTo" => $_SERVER['PHP_SELF']]); } // If the user is logging in. if (isset($_REQUEST[$saml_sso])) { $sp = $_REQUEST[$saml_sso]; $as = new SimpleSAML_Auth_Simple($sp); $as->requireAuth(); $user = array('sp' => $sp, 'authed' => $as->isAuthenticated(), 'idp' => $as->getAuthData('saml:sp:IdP'), 'nameId' => $as->getAuthData('saml:sp:NameID')['Value'], 'attributes' => $as->getAttributes()); $_SESSION[$user_session_key] = $user; } ?> <!DOCTYPE html> <html> <head> <title><?php echo $title; ?> </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap --> <link href="<?php echo $bootstrap_cdn_css_url;
$source = get_input("saml_source"); if (!empty($source)) { $label = simplesaml_get_source_label($source); // if(simplesaml_is_enabled_source($source)){ try { $saml_auth = new SimpleSAML_Auth_Simple($source); } catch (Exception $e) { register_error(elgg_echo("simplesaml:error:class", array($e->getMessage()))); forward($forward_url); } // make sure we can forward you to the correct url if (!isset($_SESSION["last_forward_from"])) { $_SESSION["last_forward_from"] = $_SERVER["REFERER"]; } // login with SAML if (!$saml_auth->isAuthenticated()) { if (subsite_manager_on_subsite()) { $site = elgg_get_site_entity(); $main_site = $site->getOwnerEntity(); $main_url = str_ireplace($site->url, $main_site->url, current_page_url()); $redirect_url = $site->url . "mod/subsite_manager/procedures/simplesaml/redirect.php"; SimpleSAML_Utilities::redirect($main_url, array("from" => $redirect_url)); } else { if (get_input("from")) { $_SESSION["last_forward_from"] = $source; } // not logged in on IDP, so do that $saml_auth->login(); } } else { // user is authenticated with IDP, so check in Elgg
/** * Process a request. * * This function never returns. * * @param Auth_OpenID_Request $request The request we are processing. */ public function processRequest(array $state) { assert('isset($state["request"])'); $request = $state['request']; $sreg_req = Auth_OpenID_SRegRequest::fromOpenIDRequest($request); $ax_req = Auth_OpenId_AX_FetchRequest::fromOpenIDRequest($request); /* In resume.php there should be a way to display data requested through sreg or ax. */ if (!$this->authSource->isAuthenticated()) { if ($request->immediate) { /* Not logged in, and we cannot show a login form. */ $this->sendResponse($request->answer(FALSE)); } $resumeURL = $this->getStateURL('resume.php', $state); $this->authSource->requireAuth(array('ReturnTo' => $resumeURL)); } $identity = $this->getIdentity(); assert('$identity !== FALSE'); /* Should always be logged in here. */ if (!$request->idSelect() && $identity !== $request->identity) { /* The identity in the request doesn't match the one of the logged in user. */ throw new SimpleSAML_Error_Exception('Logged in as different user than the one requested.'); } if ($this->isTrusted($identity, $request->trust_root)) { $trusted = TRUE; } elseif (isset($state['TrustResponse'])) { $trusted = (bool) $state['TrustResponse']; } else { if ($request->immediate) { /* Not trusted, and we cannot show a trust-form. */ $this->sendResponse($request->answer(FALSE)); } $trustURL = $this->getStateURL('trust.php', $state); SimpleSAML_Utilities::redirectTrustedURL($trustURL); } if (!$trusted) { /* The user doesn't trust this site. */ $this->sendResponse($request->answer(FALSE)); } $response = $request->answer(TRUE, NULL, $identity); //Process attributes $attributes = $this->authSource->getAttributes(); foreach ($attributes as $key => $attr) { if (is_array($attr) && count($attr) === 1) { $attributes[$key] = $attr[0]; } } $pc = new SimpleSAML_Auth_ProcessingChain($this->authProc, array(), 'idp'); $state = array('Attributes' => $attributes, 'isPassive' => TRUE); $pc->processStatePassive(&$state); $attributes = $state['Attributes']; //Process SREG requests $sreg_resp = Auth_OpenID_SRegResponse::extractResponse($sreg_req, $attributes); $sreg_resp->toMessage($response->fields); //Process AX requests $ax_resp = new Auth_OpenID_AX_FetchResponse(); foreach ($ax_req->iterTypes() as $type_uri) { if (isset($attributes[$type_uri])) { $ax_resp->addValue($type_uri, $attributes[$type_uri]); } } $ax_resp->toMessage($response->fields); /* The user is authenticated, and trusts this site. */ $this->sendResponse($response); }
* authenticated, the message will be shown. * * Since POST parameters are preserved during requireAuth-processing, * the message will be presented to the user after the authentication. */ $as->requireAuth(); $message = $_POST['message']; } else { $message = NULL; } /* * We set a variable depending on whether the user is authenticated or not. * This allows us to show the user a login link or a logout link depending * on the authentication state. */ $isAuth = $as->isAuthenticated(); /* * Retrieve the users attributes. We will list them if the user * is authenticated. */ $attributes = $as->getAttributes(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Simple test</title> </head> <body>
throw new Exception($message); } } if (array_key_exists('language', $_GET) && is_string($_GET['language'])) { \SimpleSAML\Locale\Language::setLanguageCookie($_GET['language']); } $ticketStoreConfig = $casconfig->getValue('ticketstore', array('class' => 'casserver:FileSystemTicketStore')); $ticketStoreClass = SimpleSAML_Module::resolveClass($ticketStoreConfig['class'], 'Cas_Ticket'); $ticketStore = new $ticketStoreClass($casconfig); $ticketFactoryClass = SimpleSAML_Module::resolveClass('casserver:TicketFactory', 'Cas_Ticket'); $ticketFactory = new $ticketFactoryClass($casconfig); $session = SimpleSAML_Session::getSessionFromRequest(); $sessionTicket = $ticketStore->getTicket($session->getSessionId()); $sessionRenewId = $sessionTicket ? $sessionTicket['renewId'] : null; $requestRenewId = isset($_REQUEST['renewId']) ? $_REQUEST['renewId'] : null; if (!$as->isAuthenticated() || $forceAuthn && $sessionRenewId != $requestRenewId) { $query = array(); if ($sessionRenewId && $forceAuthn) { $query['renewId'] = $sessionRenewId; } if (isset($_REQUEST['service'])) { $query['service'] = $_REQUEST['service']; } if (isset($_REQUEST['renew'])) { $query['renew'] = $_REQUEST['renew']; } if (isset($_REQUEST['gateway'])) { $query['gateway'] = $_REQUEST['gateway']; } if (array_key_exists('language', $_GET)) { $query['language'] = is_string($_GET['language']) ? $_GET['language'] : null;
* without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ if (isset($_GET['samlroute'])) { require_once __DIR__ . '/lib/_autoload.php'; $saml = new \SimpleSAML_Auth_Simple('default-sp'); if (!$saml->isAuthenticated()) { /* Show login link. */ $saml->requireAuth(); } else { $user = $saml->getAttributes(); foreach ($user as $key => $value) { $user[$key] = $value[0]; } $attr = json_encode($user); header('Location: ' . $_SERVER['SCRIPT_NAME'] . '/../../index.php/service/syntarsus/login/handler?tk=' . $_GET['tk'] . '&ref=' . $_GET['ref'] . '&route=' . $_GET['samlroute'] . '&attr=' . $attr); } }
$urltogo = $_SERVER['HTTP_REFERER']; } else { $urltogo = '/'; } } if ($saml_param->dosinglelogout) { $as->logout($urltogo); assert("FALSE"); // The previous line issues a redirect } else { header('Location: ' . $urltogo); exit; } } $as->requireAuth(); $valid_saml_session = $as->isAuthenticated(); $saml_attributes = $as->getAttributes(); } catch (Exception $e) { session_write_close(); require_once '../../config.php'; require_once 'error.php'; global $CFG, $err, $PAGE, $OUTPUT; $PAGE->set_url('/auth/saml/index.php'); $PAGE->set_context(CONTEXT_SYSTEM::instance()); $pluginconfig = get_config('auth/saml'); $urltogo = $CFG->wwwroot; if ($CFG->wwwroot[strlen($CFG->wwwroot) - 1] != '/') { $urltogo .= '/'; } $err['login'] = $e->getMessage(); log_saml_error('Moodle SAML module:' . $err['login'], $pluginconfig->samllogfile);
function authenticated_via_saml(&$saml_username = NULL, &$saml_displayname = NULL) { global $SAML_options, $debug_mode, $auto_tags; if (!file_exists($SAML_options['simplesamlphp_basedir'] . '/lib/_autoload.php')) { throw new RackTablesError('Configured for SAML authentication, but simplesaml is not found.', RackTablesError::MISCONFIGURED); } require_once $SAML_options['simplesamlphp_basedir'] . '/lib/_autoload.php'; $as = new SimpleSAML_Auth_Simple($SAML_options['sp_profile']); if (!$as->isAuthenticated()) { $as->requireAuth(); } $attributes = $as->getAttributes(); $saml_username = saml_getAttributeValue($attributes, $SAML_options['usernameAttribute']); $saml_displayname = saml_getAttributeValue($attributes, $SAML_options['fullnameAttribute']); if (array_key_exists('groupListAttribute', $SAML_options)) { foreach (saml_getAttributeValues($attributes, $SAML_options['groupListAttribute']) as $autotag) { $auto_tags[] = array('tag' => '$sgcn_' . $autotag); } } return $as->isAuthenticated(); }
qui ensuite demande à l'IdP de tuer la session en cours. */ // Redirection mise en dure ici pour l'instant, tant que ça ne concerne que Bordeaux... // Remarque : le code 307 peut causer des soucis ; le code 302 semble mieux. http://fr.wikipedia.org/wiki/Liste_des_codes_HTTP header('Status: 302 Found', TRUE, 302); header('Location: https://ent2d.ac-bordeaux.fr/Shibboleth.sso/Logout'); exit; } // //////////////////////////////////////////////////////////////////////////////////////////////////// // Déconnexion de GEPI avec le protocole SAML // //////////////////////////////////////////////////////////////////////////////////////////////////// if ($connexion_mode == 'gepi') { // Charger l'autoload de la librairie SimpleSAMLphp (qui ne peut être intégré de façon simple dans le _loader par un unique appel de classe (comme phpCAS). require CHEMIN_DOSSIER_SACOCHE . '_lib' . DS . 'SimpleSAMLphp' . DS . 'lib' . DS . '_autoload.php'; // Mise en session d'informations dont SimpleSAMLphp a besoin ; utiliser des constantes ne va pas car Gepi fait un appel à SimpleSAMLphp en court-circuitant SACoche pour vérifier la légitimité de l'appel. $_SESSION['SACoche-SimpleSAMLphp'] = array('GEPI_URL' => $gepi_url, 'GEPI_RNE' => $gepi_rne, 'GEPI_CERTIFICAT_EMPREINTE' => $gepi_certificat_empreinte, 'SIMPLESAMLPHP_BASEURLPATH' => substr($_SERVER['SCRIPT_NAME'], 1, -9) . '_lib/SimpleSAMLphp/www/', 'WEBMESTRE_NOM' => WEBMESTRE_NOM, 'WEBMESTRE_PRENOM' => WEBMESTRE_PRENOM, 'WEBMESTRE_COURRIEL' => WEBMESTRE_COURRIEL); // Initialiser la classe $auth = new SimpleSAML_Auth_Simple('distant-gepi-saml'); // Déconnexion de GEPI if ($auth->isAuthenticated()) { $auth->logout(); exit; } elseif (isset($_SESSION['SimpleSAMLphp_SESSION'])) { // On revient très probablement de la déconnexion de GEPI (en effet, au contraire de CAS, la page de déconnexion distante renvoie vers l'application au lieu de marquer un arrêt). unset($_SESSION['SimpleSAMLphp_SESSION']); exit_error('Deconnexion de Gepi', 'Déconnexion du service d\'authentification Gepi effectuée.<br />Fermez votre navigateur par sécurité.'); } else { // Bizarre... a priori on n'était pas connecté à GEPI... appel direct ? exit_error('Deconnexion de Gepi', 'Votre authentification sur Gepi n\'a pas été retrouvée.<br />Fermez votre navigateur par sécurité pour être certain d\'en être déconnecté.'); } }
public function connectAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $referer = trim($this->session->connectreferer); if (trim($referer) === "") { $referer = $_SERVER["HTTP_REFERER"]; $this->session->connectreferer = $referer; } if (trim($referer) === "") { $referer = "https://" . $_SERVER["HTTP_HOST"]; } //check if user is loggedin if (isset($this->session->userid) === false || is_numeric($this->session->userid) === false || intval($this->session->userid) <= 0) { header("Location: " . $referer); unset($this->session->connectreferer); return; } //Check if source is given $source = trim($this->_getParam("source")); if ($source == "") { header("Location: " . $referer); unset($this->session->connectreferer); return; } $authsource = str_replace("-sp", "", strtolower(trim($source))); $connectsource = str_replace("-sp", "-connect", $source); require_once SamlAuth::LIB_AUTOLOAD; //Initialize SAML $config = SimpleSAML_Configuration::getInstance(); $t = new SimpleSAML_XHTML_Template($config, 'core:authsource_list.tpl.php'); $t->data['sources'] = SimpleSAML_Auth_Source::getSourcesMatch('-connect'); if (!in_array($connectsource, $t->data['sources'])) { header("Location: " . $referer); unset($this->session->connectreferer); $this->session->userError = array("title" => "Could not proceed with user account connection", "message" => "You tried to connect to a " . $authsource . " account. This type of connection is not supported."); exit; } //Check if SAML Authentication user account for connection is already authenticated $as = new SimpleSAML_Auth_Simple($connectsource); //In case a user is already authenticated with the source logout and redirect here again if ($as->isAuthenticated()) { $as->logout('https://' . $_SERVER["SERVER_NAME"] . '/saml/connect?source=' . $source); return; } //SAML Authentication new user account for connection //$as = new SimpleSAML_Auth_Simple($connectsource); //Do the login $as->login(array("ReturnTo" => "https://" . $_SERVER["HTTP_HOST"] . "/saml/postconnect?source=" . $source, "ErrorUrl" => "https://" . $_SERVER["HTTP_HOST"] . "/saml/postconnecterror?source=" . $source)); return; }