requireAuth() public method

If the user is authenticated, this function returns immediately. If the user isn't authenticated, this function will authenticate the user with the authentication source, and then return the user to the current page. This function accepts an array $params, which controls some parts of the authentication. See the login() method for a description.
public requireAuth ( array $params = [] )
$params array Various options to the authentication request. See the documentation.
Example #1
1
 function procesarFormulario()
 {
     $saml_lib_path = '/var/simplesamlphp/lib/_autoload.php';
     require_once $saml_lib_path;
     // $aplication_base_url = 'http://10.20.0.38/splocal/';
     $aplication_base_url = $this->host . $this->site . '/';
     $source = 'SPcrono';
     // 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
     $login_params = array('ReturnTo' => $aplication_base_url . 'index.php');
     $as->requireAuth($login_params);
     return false;
 }
Example #2
1
 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="#">&times;</a>', '</p>');
 }
Example #3
0
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     if ($this->auth->guest()) {
         if ($request->ajax()) {
             return response('Unauthorized.', 401);
         } else {
             //return redirect()->guest('auth/login')
             //tsipizic for SAML
             //login user and get attributes
             $as = new \SimpleSAML_Auth_Simple('default-sp');
             $as->requireAuth();
             $attributes = $as->getAttributes();
             //create user if he does not exist and log him in
             $mail = $attributes['mail'][0];
             $db_user = User::where('mail', $mail)->first();
             if ($db_user) {
                 Auth::login($db_user);
             } else {
                 $user = new User();
                 $user->mail = $mail;
                 $user->save();
                 Auth::login($user);
             }
         }
     }
     return $next($request);
 }
Example #4
0
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;
}
 /**
  * Performs an authentication attempt using SimpleSAMLphp
  *
  * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
  * @return Zend_Auth_Result
  */
 public function authenticate()
 {
     require_once LIBRARY_PATH . '/simplesamlphp/lib/_autoload.php';
     $as = new SimpleSAML_Auth_Simple('default-sp');
     $as->requireAuth();
     // If SimpleSAMLphp didn't stop it, then the user is logged in.
     return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $as->getAttributes(), array("Authentication Successful"));
 }
Example #6
0
 /**
  * Check that the user has access to the statistics.
  *
  * If the user doesn't have access, send the user to the login page.
  */
 public static function checkAccess(SimpleSAML_Configuration $statconfig)
 {
     $protected = $statconfig->getBoolean('protected', FALSE);
     $authsource = $statconfig->getString('auth', NULL);
     $allowedusers = $statconfig->getValue('allowedUsers', NULL);
     $useridattr = $statconfig->getString('useridattr', 'eduPersonPrincipalName');
     $acl = $statconfig->getValue('acl', NULL);
     if ($acl !== NULL && !is_string($acl) && !is_array($acl)) {
         throw new SimpleSAML_Error_Exception('Invalid value for \'acl\'-option. Should be an array or a string.');
     }
     if (!$protected) {
         return;
     }
     if (SimpleSAML\Utils\Auth::isAdmin()) {
         // User logged in as admin. OK.
         SimpleSAML_Logger::debug('Statistics auth - logged in as admin, access granted');
         return;
     }
     if (!isset($authsource)) {
         // If authsource is not defined, init admin login.
         SimpleSAML\Utils\Auth::requireAdmin();
     }
     /* We are using an authsource for login. */
     $as = new SimpleSAML_Auth_Simple($authsource);
     $as->requireAuth();
     // User logged in with auth source.
     SimpleSAML_Logger::debug('Statistics auth - valid login with auth source [' . $authsource . ']');
     // Retrieving attributes
     $attributes = $as->getAttributes();
     if (!empty($allowedusers)) {
         // Check if userid exists
         if (!isset($attributes[$useridattr][0])) {
             throw new Exception('User ID is missing');
         }
         // Check if userid is allowed access..
         if (in_array($attributes[$useridattr][0], $allowedusers)) {
             SimpleSAML_Logger::debug('Statistics auth - User granted access by user ID [' . $attributes[$useridattr][0] . ']');
             return;
         }
         SimpleSAML_Logger::debug('Statistics auth - User denied access by user ID [' . $attributes[$useridattr][0] . ']');
     } else {
         SimpleSAML_Logger::debug('Statistics auth - no allowedUsers list.');
     }
     if (!is_null($acl)) {
         $acl = new sspmod_core_ACL($acl);
         if ($acl->allows($attributes)) {
             SimpleSAML_Logger::debug('Statistics auth - allowed access by ACL.');
             return;
         }
         SimpleSAML_Logger::debug('Statistics auth - denied access by ACL.');
     } else {
         SimpleSAML_Logger::debug('Statistics auth - no ACL configured.');
     }
     throw new SimpleSAML_Error_Exception('Access denied to the current user.');
 }
Example #7
0
 /**
  * @METHOD crear_sesion
  *
  * Crea una nueva sesión en la base de datos.
  * @PARAM usuario_aplicativo
  * @PARAM nivel_acceso
  * @PARAM expiracion
  * @PARAM conexion_id
  *
  * @return boolean
  * @access public
  */
 function crearSesion()
 {
     $saml_lib_path = '/var/simplesamlphp/lib/_autoload.php';
     require_once $saml_lib_path;
     // $aplication_base_url = 'http://10.20.0.38/splocal/';
     $aplication_base_url = $this->hostSSO . $this->site . '/';
     $source = $this->SPSSO;
     // 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
     $login_params = array('ReturnTo' => $aplication_base_url . 'index.php');
     $as->requireAuth($login_params);
     $atributos = $as->getAttributes();
     $this->sesionUsuario->crearSesion($atributos['usuario'][0]);
     return $atributos;
 }
 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;
 }
Example #9
0
 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&eacute;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');
 }
Example #10
0
 public function loginAction()
 {
     //$logger = Zend_Registry::get('logger');
     //$logger->log('bericht hier', Zend_Log::INFO);
     $this->_helper->viewRenderer->setNoRender(true);
     $this->_helper->layout->disableLayout();
     $config = Zend_Registry::get('config');
     $url = $config->system->web->url . $config->system->web->baseurl;
     $as = new SimpleSAML_Auth_Simple('klavsts');
     $options = array('saml:IsPassive' => true, 'KeepPost' => false, 'ReturnTo' => $this->view->url(), 'ErrorURL' => $url . '/index/unauthorized');
     $as->requireAuth($options);
     $attributes = $as->getAttributes();
     $user = new SxCms_User_Klav();
     $user->setFirstName($attributes['urn:klav:data:Username'][0]);
     $user->setEmail($attributes['urn:klav:data:Email'][0]);
     $user->setDoccheck($attributes['urn:klav:data:doccheck'][0]);
     $user->setFarmanager($attributes['urn:klav:data:farmanager']);
     $user->setClientId($attributes['urn:klav:data:client'][0]);
     $user->setLanguage($attributes['urn:klav:data:taal_cd'][0]);
     $user->setGroups($attributes['urn:klav:groups']);
     $user->setDocmanager($attributes['urn:klav:docmanager']);
     $user->setClients($attributes['urn:klav:clients']);
     $user->setNamed($attributes['urn:klav:data:named'][0]);
     $user->setSessionId($attributes['urn:klav:sessionid'][0]);
     $user->setUsername($attributes['UserName'][0]);
     $mapper = new SxCms_Group_DataMapper();
     $groups = $attributes['groups'];
     foreach ($groups as $samlId) {
         $group = $mapper->getBySamlId($samlId);
         if ($group) {
             $user->addGroup($group);
         }
     }
     $auth = Zend_Auth::getInstance();
     $storage = $auth->getStorage();
     $storage->write($user);
     // full requested url
     $burl = $this->_getParam('url', '');
     $burl = base64_decode($burl);
     $burl = urldecode($burl);
     $burl = 'http://' . $this->getRequest()->getHttpHost() . $burl;
     $this->_helper->redirector->setGotoUrl($burl);
 }
Example #11
0
 /**
  * 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));
 }
Example #12
0
<?php

include dirname(__FILE__) . "/bootstrap.php";
$returnTo = isset($_REQUEST["returnTo"]) ? $_REQUEST["returnTo"] : HOME_URL;
if (defined("ENV") && ENV !== "dev") {
    $sp = defined("SIMPLE_SAML_SP") ? SIMPLE_SAML_SP : 'default-sp';
    $saml = new SimpleSAML_Auth_Simple($sp);
    $saml->requireAuth(['ReturnTo' => $returnTo, 'KeepPost' => false]);
} else {
    header("Location: " . $returnTo);
    setcookie("beta_dev_loggedin", true);
    die;
}
Example #13
0
<?php

/**
 * Endpoint for logging in with an authentication source.
 *
 * @package simpleSAMLphp
 * @version $Id$
 */
if (!is_string($_REQUEST['ReturnTo'])) {
    throw new SimpleSAML_Error_BadRequest('Missing ReturnTo parameter.');
}
if (!is_string($_REQUEST['AuthId'])) {
    throw new SimpleSAML_Error_BadRequest('Missing AuthId parameter.');
}
$as = new SimpleSAML_Auth_Simple($_REQUEST['AuthId']);
$as->requireAuth(array('ReturnTo' => $_REQUEST['ReturnTo']));
SimpleSAML_Utilities::redirect($_REQUEST['ReturnTo']);
Example #14
0
<?php

/**
 * ownCloud - user_saml
 *
 * @author Sixto Martin <*****@*****.**>
 * @copyright 2012 Yaco Sistemas // CONFIA
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
$sspPath = OCP\Config::getAppValue('user_saml', 'saml_ssp_path', '');
$spSource = OCP\Config::getAppValue('user_saml', 'saml_sp_source', '');
$autocreate = OCP\Config::getAppValue('user_saml', 'saml_autocreate', false);
if (!empty($sspPath) && !empty($spSource)) {
    include_once $sspPath . "/lib/_autoload.php";
    $auth = new SimpleSAML_Auth_Simple($spSource);
    $auth->requireAuth();
}
 public function processLogin()
 {
     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);
     $_SESSION['chartValid'] = false;
     $ppo = new CopixPPO();
     $ppo->user = _currentUser();
     if ($ppo->user->isConnected()) {
         $url_return = CopixUrl::get('kernel||doSelectHome');
         /*
          * PATCH FOR CHARTE
          */
         $this->user->forceReload();
         if (!$this->service('charte|CharteService')->checkUserValidation()) {
             $this->flash->redirect = $url_return;
             return $this->go('charte|charte|valid');
         }
         return _arRedirect($url_return);
         //return new CopixActionReturn (COPIX_AR_REDIRECT, $url_return);
     } else {
         $as->requireAuth();
         $attributes = $as->getAttributes();
         /*
         echo "<pre>";
         print_r($attributes);
         die();
         */
         $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];
         } else {
             $ppo->saml_error = 'bad-conf-uidattribute';
             return _arPpo($ppo, 'saml-error.tpl');
         }
         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->saml_error = 'no-iconito-user';
                 return _arPpo($ppo, 'saml-error.tpl');
             }
         }
     }
     // $as->getLoginURL();
     /*
     if (!$as->isAuthenticated()) {
     	$url = SimpleSAML_Module::getModuleURL('core/authenticate.php', array('as' => $asId));
     	$params = array(
     		'ErrorURL' => CopixUrl::get ('auth|saml|test_error'),
     		'ReturnTo' => CopixUrl::get ('auth|saml|test_ok'),
     	);
     	$as->login($params);
     }
     */
     /*
     $attributes = $as->getAttributes();
     
     echo "<pre>";
     print_r($attributes);
     die();
     */
 }
*                    'token' corresponding to the implicit grant flow is supported.
*    client_id     - a configured id string agreed upon by any given client and authorization server
*    redirect_uri  - an optional configured uri to redirect the user agent to after authorization is granted or denied
*    scope         - optional configured scope strings agreed upon by any given client and authorization server
*    state         - optional string which clients can use to maintain state during authentication and authorization flows.
*/
session_cache_limiter('nocache');
$config = SimpleSAML_Configuration::getConfig('module_oauth2server.php');
$clientStore = new sspmod_oauth2server_OAuth2_ClientStore($config);
if (isset($_REQUEST['client_id'])) {
    $client = $clientStore->getClient($_REQUEST['client_id']);
}
if (isset($client)) {
    $as = new SimpleSAML_Auth_Simple($config->getValue('authsource'));
    $params = sspmod_oauth2server_Utility_Uri::calculateScopingParameters($client);
    $as->requireAuth($params);
    if (array_key_exists('redirect_uri', $client) && is_array($client['redirect_uri']) && count($client['redirect_uri']) > 0) {
        $returnUri = isset($_REQUEST['redirect_uri']) ? $_REQUEST['redirect_uri'] : $client['redirect_uri'][0];
        $legalRedirectUri = sspmod_oauth2server_Utility_Uri::validateRedirectUri($returnUri, $client);
        if ($legalRedirectUri) {
            $requestedScopes = sspmod_oauth2server_Utility_Uri::augmentRequestedScopesWithRequiredScopes($client, isset($_REQUEST['scope']) ? explode(' ', $_REQUEST['scope']) : array());
            $invalidScopes = sspmod_oauth2server_Utility_Uri::findInvalidScopes($client, $requestedScopes);
            if (count($invalidScopes) == 0) {
                if (isset($_REQUEST['response_type']) && ($_REQUEST['response_type'] === 'code' || $_REQUEST['response_type'] === 'token')) {
                    $state = array('clientId' => $_REQUEST['client_id'], 'redirectUri' => isset($_REQUEST['redirect_uri']) ? $_REQUEST['redirect_uri'] : null, 'requestedScopes' => array_unique($requestedScopes), 'returnUri' => $returnUri, 'response_type' => $_REQUEST['response_type']);
                    if (array_key_exists('state', $_REQUEST)) {
                        $state['state'] = $_REQUEST['state'];
                    }
                    $stateId = SimpleSAML_Auth_State::saveState($state, 'oauth2server:authorization/consent');
                    $consentUri = SimpleSAML\Utils\HTTP::addURLParameters(SimpleSAML_Module::getModuleURL('oauth2server/authorization/consent.php'), array('stateId' => $stateId));
                    SimpleSAML\Utils\HTTP::redirectTrustedURL($consentUri);
Example #17
0
   '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');
 //on forge une extension SAML pour tramsmettre l'établissement précisé dans SACoche
 $ext = array();
 if($BASE)
 {
   $dom = new DOMDocument();
   $ce = $dom->createElementNS('gepi_name_space', 'gepi_name_space:organization', $BASE);
   $ext[] = new SAML2_XML_Chunk($ce);
 }
 $auth->requireAuth( array('saml:Extensions'=>$ext) );
 // Tester si le user est authentifié, rediriger sinon
 $auth->requireAuth();
 // Récupérer l'identifiant Gepi de l'utilisateur authentifié pour le traiter dans l'application
 $attr = $auth->getAttributes();
 $login_GEPI = $attr['USER_ID_GEPI'][0];
 // Comparer avec les données de la base
 list($auth_resultat,$auth_DB_ROW) = SessionUser::tester_authentification_utilisateur( $BASE , $login_GEPI /*login*/ , FALSE /*password*/ , 'gepi' /*mode_connection*/ );
 if($auth_resultat!='ok')
 {
   exit_error( 'Incident authentification Gepi' /*titre*/ , $auth_resultat /*contenu*/ );
 }
 // Connecter l'utilisateur
 SessionUser::initialiser_utilisateur($BASE,$auth_DB_ROW);
 // Pas de redirection (passage possible d'infos en POST à conserver), on peut laisser le code se poursuivre.
 return; // Ne pas exécuter la suite de ce fichier inclus.
 /**
  * @return bool true if the user is correctly authenticated, false if there was an error with login
  * NB: If the user is not authenticated, they will be redirected to RealMe to login, so a boolean false return here
  * indicates that there was a failure during the authentication process (perhaps a communication issue)
  */
 public function enforceLogin()
 {
     $auth = new SimpleSAML_Auth_Simple($this->config()->auth_source_name);
     $auth->requireAuth(array('ReturnTo' => '/Security/realme/acs', 'ErrorURL' => '/Security/realme/error'));
     $loggedIn = false;
     $authData = $this->getAuthData($auth);
     if (is_null($authData)) {
         // no-op, $loggedIn stays false and no data is written
     } else {
         $this->config()->user_data = $authData;
         Session::set('RealMeSessionDataSerialized', serialize($authData));
         $loggedIn = true;
     }
     return $loggedIn;
 }
Example #19
0
 /**
  * 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);
 }
Example #20
0
<?php

/**
 * Endpoint for logging in with an authentication source.
 *
 * @package simpleSAMLphp
 */
if (!is_string($_REQUEST['ReturnTo'])) {
    throw new SimpleSAML_Error_BadRequest('Missing ReturnTo parameter.');
}
if (!is_string($_REQUEST['AuthId'])) {
    throw new SimpleSAML_Error_BadRequest('Missing AuthId parameter.');
}
/*
 * Setting up the options for the requireAuth() call later..
 */
$options = array('ReturnTo' => \SimpleSAML\Utils\HTTP::checkURLAllowed($_REQUEST['ReturnTo']));
/*
 * Allows a saml:idp query string parameter specify the IdP entity ID to be used
 * as used by the DiscoJuice embedded client.
 */
if (!empty($_REQUEST['saml:idp'])) {
    $options['saml:idp'] = $_REQUEST['saml:idp'];
}
$as = new SimpleSAML_Auth_Simple($_REQUEST['AuthId']);
$as->requireAuth($options);
\SimpleSAML\Utils\HTTP::redirectTrustedURL($options['ReturnTo']);
Example #21
0
 * 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);
    }
}
Example #22
0
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();
}
Example #23
0
<?php

try {
    if (!isset($_GET['SourceID'])) {
        throw new SimpleSAML_Error_BadRequest('Missing SourceID parameter');
    }
    $sourceId = $_GET['SourceID'];
    $as = new SimpleSAML_Auth_Simple($sourceId);
    $as->requireAuth();
    header('Content-Type: text/plain; charset=utf-8');
    echo "OK\n";
} catch (Exception $e) {
    header('HTTP/1.0 500 Internal Server Error');
    header('Content-Type: text/plain; charset=utf-8');
    echo "ERROR\n";
    echo $e->getMessage() . "\n";
}
Example #24
0
 public function login($url, $cID)
 {
     $as = new SimpleSAML_Auth_Simple('example-static');
     $as->requireAuth();
     $attributes = $as->getAttributes();
     //$this->get_metadata($cID);
     $this->CI->session->set_userdata('cID', $cID);
     //$config = SimpleSAML_Configuration::getInstance();
     //$session = SimpleSAML_Session::getInstance();
     //echo "<pre>"; print_r($session); echo "</pre>"; die();
     redirect($url);
 }
 private function getAttributesInitToken()
 {
     require_once '/var/simplesamlphp/lib/_autoload.php';
     $auth = new \SimpleSAML_Auth_Simple('default-sp');
     $auth->requireAuth();
     \Factory::$properties['LOGOUTURL'] = $auth->getLogoutURL('https://' . gethostname());
     $attributes = $auth->getAttributes();
     if (!empty($attributes)) {
         // which idp did the user select?
         $idp = $auth->getAuthData('saml:sp:IdP');
         // EGI IdP
         if ($idp == 'https://www.egi.eu/idp/shibboleth') {
             // For EGI federated id:
             //$dnAttribute = $attributes['urn:oid:1.3.6.1.4.1.11433.2.2.1.9'][0];
             //if (!empty($dnAttribute)) {
             //    $this->principle = str_replace("emailAddress=", "Email=", $dnAttribute);
             //    $this->userDetails = array('AuthenticationRealm' => array('EGI_SSO_IDP'));
             //}
             $nameID = $auth->getAuthData('saml:sp:NameID');
             $this->principle = $nameID['Value'];
             $this->userDetails = array('AuthenticationRealm' => array('EGI_SSO_IDP'));
             // iterate the attributes and store in the userDetails
             // Each attribute name can be used as an index into $attributes to obtain the value.
             // Every attribute value is an array - a single-valued attribute is an array of a single element.
             foreach ($attributes as $key => $valArray) {
                 $this->userDetails[$key] = $valArray;
             }
         } else {
             if ($idp == 'https://unity.eudat-aai.fz-juelich.de:8443/saml-idp/metadata') {
                 // For EUDAT federated id:
                 //$dnAttribute = $attributes['urn:oid:2.5.4.49'][0];
                 //$dnAttribute = $attributes['unity:identity:persistent'][0];
                 //print_r($attributes);
                 $nameID = $auth->getAuthData('saml:sp:NameID');
                 $this->principle = $nameID['Value'];
                 $this->userDetails = array('AuthenticationRealm' => array('EUDAT_SSO_IDP'));
                 // iterate the attributes and store in the userDetails
                 // Each attribute name can be used as an index into $attributes to obtain the value.
                 // Every attribute value is an array - a single-valued attribute is an array of a single element.
                 foreach ($attributes as $key => $valArray) {
                     $this->userDetails[$key] = $valArray;
                 }
             }
         }
     }
 }
Example #26
0
 public function samlAction()
 {
     require_once SamlAuth::LIB_AUTOLOAD;
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
     //In case of external service using AppDB as a SP
     if (isset($_GET['callbackUrl']) && trim($_GET['callbackUrl']) !== '') {
         $this->session->authreferer = trim($_GET['callbackUrl']);
     } else {
         if (isset($this->session->authreferer) === false) {
             $this->session->authreferer = $_SERVER["HTTP_REFERER"];
         }
     }
     $source = $this->_getParam("source");
     if ($source == null) {
         $source = "";
     }
     //Check if user is already logged in
     if (SamlAuth::isAuthenticated() !== false) {
         if (isset($this->session->authreferer) && trim($this->session->authreferer) !== "") {
             $this->session->authreferer = str_replace("http://", "https://", $this->session->authreferer);
             header("Location: " . $this->session->authreferer);
         } else {
             header("Location: " . "https://" . $_SERVER['HTTP_HOST']);
         }
         return;
     } else {
         if (isset($this->session) && $this->session->isNewUser === true) {
             header("Location: " . "https://" . $_SERVER['HTTP_HOST']);
             return;
         }
     }
     $config = SimpleSAML_Configuration::getInstance();
     $t = new SimpleSAML_XHTML_Template($config, 'core:authsource_list.tpl.php');
     $t->data['sources'] = SimpleSAML_Auth_Source::getSourcesMatch('-sp');
     if (!in_array($source, $t->data['sources'])) {
         header("Location: " . "https://" . $_SERVER['HTTP_HOST']);
         exit;
     }
     $as = new SimpleSAML_Auth_Simple($source);
     if (!$as->isAuthenticated()) {
         $as->requireAuth();
     }
     $attributes = $as->getAttributes();
     $uid = $attributes['idp:uid'][0];
     $_SESSION['identity'] = $uid;
     $_SESSION['logouturl'] = $as->getLogoutURL();
     $this->session->samlattrs = $attributes;
     $this->session->samlauthsource = $source;
     $this->_helper->redirector('postauth');
 }
Example #27
0
<?php

require_once dirname(dirname(dirname(__FILE__))) . "/lib/bootstrap.php";
if (defined("ENV") && ENV !== "dev") {
    $saml_include = defined("SIMPLE_SAML_INCLUDE_PATH") ? SIMPLE_SAML_INCLUDE_PATH : "simplesamlphp/lib/_bootstrap.php";
    require_once $saml_include;
}
$returnTo = isset($_REQUEST["returnTo"]) ? $_REQUEST["returnTo"] : HOME_URL;
if (defined("ENV") && ENV !== "dev") {
    $sp = defined("SIMPLE_SAML_SP") ? SIMPLE_SAML_SP : 'default-sp';
    $saml = new SimpleSAML_Auth_Simple($sp);
    if (!$saml->isAuthenticated()) {
        $saml->requireAuth(array('ReturnTo' => HOME_URL . "auth/process.php?returnTo=" . $returnTo));
    } else {
        include "process.php";
    }
} else {
    include "process.php";
}