The session will have a duration and validity, and also cache information about the different federation protocols, as Shibboleth and SAML 2.0. On the IdP side the Session class holds information about all the currently logged in SPs. This is used when the user initiates a Single-Log-Out.
Author: Andreas Åkre Solberg, UNINETT AS. (andreas.solberg@uninett.no)
 /**
  * Save a session to the data store.
  *
  * @param SimpleSAML_Session $session The session object we should save.
  */
 public function saveSession(SimpleSAML_Session $session)
 {
     $sessionId = $session->getSessionId();
     $config = SimpleSAML_Configuration::getInstance();
     $sessionDuration = $config->getInteger('session.duration', 8 * 60 * 60);
     $expire = time() + $sessionDuration;
     $this->store->set('session', $sessionId, $session, $expire);
 }
 /**
  * Create and set new session id.
  *
  * @return string  The new session id.
  */
 public function newSessionId()
 {
     $this->session_id = self::createSessionID();
     SimpleSAML_Session::createSession($this->session_id);
     $this->setCookie($this->cookie_name, $this->session_id);
     return $this->session_id;
 }
 public function process(&$state)
 {
     assert('is_array($state)');
     if (empty($state['Expire']) || empty($state['Authority'])) {
         return;
     }
     $now = time();
     $delta = $state['Expire'] - $now;
     $globalConfig = SimpleSAML_Configuration::getInstance();
     $sessionDuration = $globalConfig->getInteger('session.duration', 8 * 60 * 60);
     /* Extend only if half of session duration already passed */
     if ($delta >= $sessionDuration * 0.5) {
         return;
     }
     /* Update authority expire time */
     $session = SimpleSAML_Session::getSessionFromRequest();
     $session->setAuthorityExpire($state['Authority']);
     /* Update session cookies duration */
     /* If remember me is active */
     $rememberMeExpire = $session->getRememberMeExpire();
     if (!empty($state['RememberMe']) && $rememberMeExpire !== NULL && $globalConfig->getBoolean('session.rememberme.enable', FALSE)) {
         $session->setRememberMeExpire();
         return;
     }
     /* Or if session lifetime is more than zero */
     $sessionHandler = SimpleSAML_SessionHandler::getSessionHandler();
     $cookieParams = $sessionHandler->getCookieParams();
     if ($cookieParams['lifetime'] > 0) {
         $session->updateSessionCookies();
     }
 }
 /**
  * When login is complete, save the SSPAuthentication object to the session
  */
 public final function loginComplete()
 {
     //Use the same session as SimpleSAMLphp to avoid session state loss
     Session::start(SimpleSAML_Session::getInstance()->getSessionId());
     Session::set('ssp_current_auth_source', $this->getAuthSource()->getAuthId());
     Session::set('ssp_current_auth_class', get_class($this));
     Session::save();
 }
示例#5
0
function getUser(SimpleSAML_Session $session, ConfigProxy $janus_config)
{
    // Get data from config
    /** @var string $useridattr */
    $useridattr = $janus_config->getValue('useridattr', 'eduPersonPrincipalName');
    // Validate user
    $attributes = $session->getAttributes();
    // Check if userid exists
    if (!isset($attributes[$useridattr])) {
        echo json_encode(array('status' => 'user_id_is_missing'));
        exit;
    }
    $userid = $attributes[$useridattr][0];
    $user = new sspmod_janus_User();
    $user->setUserid($userid);
    $user->load(sspmod_janus_User::USERID_LOAD);
    return $user;
}
 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;
 }
示例#7
0
文件: Error.php 项目: hukumonline/yii
 /**
  * Display this error.
  *
  * This method displays a standard simpleSAMLphp error page and exits.
  */
 public function show()
 {
     $this->setHTTPCode();
     $session = SimpleSAML_Session::getInstance();
     if ($this->cause !== NULL) {
         $e = $this->cause;
     } else {
         $e = $this;
     }
     SimpleSAML_Utilities::fatalError($session->getTrackID(), $this->errorCode, $e);
 }
 public static function checkLoggedAndSameAuth()
 {
     $session = SimpleSAML_Session::getInstance();
     if ($session->isAuthenticated()) {
         $uregconf = SimpleSAML_Configuration::getConfig('module_selfregister.php');
         /* Get a reference to our authentication source. */
         $asId = $uregconf->getString('auth');
         if ($session->getAuthority() == $asId) {
             return new SimpleSAML_Auth_Simple($asId);
         }
     }
     return false;
 }
示例#9
0
 /**
  * Apply filter to add the UID attribute.
  *
  * @param array &$request  The current request
  */
 public function process(&$request)
 {
     assert('is_array($request)');
     assert('array_key_exists("Attributes", $request)');
     $authModule = NULL;
     // Fetch Auth module
     if (array_key_exists("SimpleSAML_Auth_State.stage", $request)) {
         $authStage = implode(":", array_slice(explode(':', $request["SimpleSAML_Auth_State.stage"]), 0, -1));
         $authId = $authStage . ':AuthId';
         $authModule = $request[$authId];
     } else {
         if (isset($request['AuthnInstant']) && isset($request['Expire'])) {
             // Probably dealing with a cached response
             $cachedAuthModule = SimpleSAML_Session::getInstance()->getData(sspmod_multiauth_Auth_Source_MultiAuth::SESSION_SOURCE, 'multi');
             if ($cachedAuthModule) {
                 $authModule = $cachedAuthModule;
             }
         }
     }
     if (!isset($authModule)) {
         throw new Exception("Auth module not found?!?!");
     }
     $attributes =& $request['Attributes'];
     $filter = null;
     // Set or replace the filter attribute
     if (array_key_exists($authModule, $this->map)) {
         $filter = $this->map[$authModule];
     }
     switch ($filter) {
         case 'GOOGLE':
             $attributes['uid'] = $this->_useEmailAsUid($attributes);
             break;
         case 'YAHOO':
             $attributes['uid'] = $this->_useEmailAsUid($attributes);
             break;
         case 'HYVES':
             if (!array_key_exists('openid.local_id', $attributes)) {
                 throw new Exception('No local id attribute provided! Cannot use it as UID');
             }
             $attributes['uid'] = str_replace('.hyves.nl/', '', str_replace('http://', '', $attributes['openid.local_id']));
             break;
         default:
             if (!array_key_exists('uid', $attributes)) {
                 throw new Exception('No UID set?!?!');
             }
             break;
     }
 }
示例#10
0
 /**
  * @deprecated This method will be removed in SSP 2.0.
  */
 public static function initLogoutReturn($returnURL, $authority)
 {
     assert('is_string($returnURL)');
     assert('is_string($authority)');
     $session = SimpleSAML_Session::getSessionFromRequest();
     $state = $session->getAuthData($authority, 'LogoutState');
     $session->doLogout($authority);
     $state['SimpleSAML_Auth_Default.ReturnURL'] = $returnURL;
     $state['LogoutCompletedHandler'] = array(get_class(), 'logoutCompleted');
     $as = SimpleSAML_Auth_Source::getById($authority);
     if ($as === NULL) {
         // The authority wasn't an authentication source...
         self::logoutCompleted($state);
     }
     $as->logout($state);
 }
 /**
  * Retrieve the session id of saved in the session cookie.
  *
  * @return string  The session id saved in the cookie.
  */
 public function getCookieSessionId()
 {
     if ($this->session_id === NULL) {
         if (self::hasSessionCookie()) {
             /* Attempt to retrieve the session id from the cookie. */
             $this->session_id = $_COOKIE[$this->cookie_name];
         }
         /* Check if we have a valid session id. */
         if (!self::isValidSessionID($this->session_id)) {
             /* We don't have a valid session. Create a new session id. */
             $this->session_id = self::createSessionID();
             SimpleSAML_Session::createSession($this->session_id);
             $this->setCookie($this->cookie_name, $this->session_id);
         }
     }
     return $this->session_id;
 }
示例#12
0
 /**
  * Constructor
  *
  * Note that the person is tied to a session and a simplesaml configuration
  * here
  */
 function __construct($person = NULL)
 {
     parent::__construct($person);
     /* Find the path to simpelsamlphp and run the autoloader */
     try {
         $sspdir = Config::get_config('simplesaml_path');
     } catch (KeyNotFoundException $knfe) {
         echo "Cannot find path to simplesaml. This install is not valid. Aborting.<br />\n";
         Logger::logEvent(LOG_ALERT, "Confusa_Auth_IdP", "__construct()", "Trying to instantiate SimpleSAMLphp without a configured path.");
         exit(0);
     }
     require_once $sspdir . '/lib/_autoload.php';
     SimpleSAML_Configuration::setConfigDir($sspdir . '/config');
     /* start a session needed for the IdP-based AuthN approach */
     $this->as = new SimpleSAML_Auth_Simple('default-sp');
     $this->session = SimpleSAML_Session::getInstance();
 }
示例#13
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);
 }
示例#14
0
 /**
  * Initializes this discovery service.
  *
  * The constructor does the parsing of the request. If this is an invalid request, it will
  * throw an exception.
  *
  * @param array $metadataSets  Array with metadata sets we find remote entities in.
  * @param string $instance  The name of this instance of the discovery service.
  */
 public function __construct(array $metadataSets, $instance)
 {
     assert('is_string($instance)');
     /* Initialize standard classes. */
     $this->config = SimpleSAML_Configuration::getInstance();
     $this->metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
     $this->session = SimpleSAML_Session::getSessionFromRequest();
     $this->instance = $instance;
     $this->metadataSets = $metadataSets;
     $this->log('Accessing discovery service.');
     /* Standard discovery service parameters. */
     if (!array_key_exists('entityID', $_GET)) {
         throw new Exception('Missing parameter: entityID');
     } else {
         $this->spEntityId = $_GET['entityID'];
     }
     if (!array_key_exists('returnIDParam', $_GET)) {
         $this->returnIdParam = 'entityID';
     } else {
         $this->returnIdParam = $_GET['returnIDParam'];
     }
     $this->log('returnIdParam initially set to [' . $this->returnIdParam . ']');
     if (!array_key_exists('return', $_GET)) {
         throw new Exception('Missing parameter: return');
     } else {
         $this->returnURL = SimpleSAML_Utilities::checkURLAllowed($_GET['return']);
     }
     $this->isPassive = FALSE;
     if (array_key_exists('isPassive', $_GET)) {
         if ($_GET['isPassive'] === 'true') {
             $this->isPassive = TRUE;
         }
     }
     $this->log('isPassive initially set to [' . ($this->isPassive ? 'TRUE' : 'FALSE') . ']');
     if (array_key_exists('IdPentityID', $_GET)) {
         $this->setIdPentityID = $_GET['IdPentityID'];
     } else {
         $this->setIdPentityID = NULL;
     }
     if (array_key_exists('IDPList', $_REQUEST)) {
         $this->scopedIDPList = $_REQUEST['IDPList'];
     }
 }
示例#15
0
 /**
  * Create and set new session id.
  *
  * @return string  The new session id.
  */
 public function newSessionId()
 {
     $session_cookie_params = session_get_cookie_params();
     if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
         throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
     }
     if (headers_sent()) {
         throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
     }
     /* Generate new (secure) session id. */
     $sessionId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
     SimpleSAML_Session::createSession($sessionId);
     if (session_id() !== '') {
         /* Session already started, close it. */
         session_write_close();
     }
     session_id($sessionId);
     session_start();
     return session_id();
 }
示例#16
0
 public function authenticate(TokenInterface $token)
 {
     /** @var string $authenticationType */
     $authenticationType = $this->config->getValue('auth', 'login-admin');
     if (php_sapi_name() === 'cli') {
         return $this->getTokenForUsername($authenticationType);
     }
     $session = \SimpleSAML_Session::getInstance();
     if (!$session->isValid($authenticationType)) {
         throw new AuthenticationException("Authsource '{$authenticationType}' is invalid");
     }
     /** @var string $userIdAttributeName */
     $userIdAttributeName = $this->config->getValue('useridattr', 'eduPersonPrincipalName');
     // Check if userid exists
     $attributes = $session->getAttributes();
     if (!isset($attributes[$userIdAttributeName])) {
         throw new AuthenticationException("Attribute '{$userIdAttributeName}' with User ID is missing.");
     }
     return $this->getTokenForUsername($attributes[$userIdAttributeName][0]);
 }
 /**
  * Create and set new session id.
  *
  * @return string The new session id.
  *
  * @throws SimpleSAML_Error_Exception If the cookie is marked as secure but we are not using HTTPS, or the headers
  * were already sent and therefore we cannot set the cookie.
  */
 public function newSessionId()
 {
     $session_cookie_params = session_get_cookie_params();
     if ($session_cookie_params['secure'] && !\SimpleSAML\Utils\HTTP::isHTTPS()) {
         throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
     }
     if (headers_sent()) {
         throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
     }
     // generate new (secure) session id
     $sessionId = bin2hex(openssl_random_pseudo_bytes(16));
     SimpleSAML_Session::createSession($sessionId);
     if (session_id() !== '') {
         // session already started, close it
         session_write_close();
     }
     session_id($sessionId);
     session_start();
     return session_id();
 }
示例#18
0
 /**
  * Retrieve the session id of saved in the session cookie.
  *
  * @return string  The session id saved in the cookie.
  */
 public function getCookieSessionId()
 {
     if (session_id() === '') {
         $session_cookie_params = session_get_cookie_params();
         if ($session_cookie_params['secure'] && !SimpleSAML_Utilities::isHTTPS()) {
             throw new SimpleSAML_Error_Exception('Session start with secure cookie not allowed on http.');
         }
         if (!self::hasSessionCookie()) {
             if (headers_sent()) {
                 throw new SimpleSAML_Error_Exception('Cannot create new session - headers already sent.');
             }
             /* Session cookie unset - session id not set. Generate new (secure) session id. */
             $sessionId = SimpleSAML_Utilities::stringToHex(SimpleSAML_Utilities::generateRandomBytes(16));
             SimpleSAML_Session::createSession($sessionId);
             session_id($sessionId);
         }
         session_start();
     }
     return session_id();
 }
示例#19
0
 /**
  * Show the error to the user.
  *
  * This function does not return.
  */
 public function show()
 {
     header('HTTP/1.0 500 Internal Server Error');
     $errorData = $this->saveError();
     $session = SimpleSAML_Session::getInstance();
     $attributes = $session->getAttributes();
     if (isset($attributes['mail'][0])) {
         $email = $attributes['mail'][0];
     } else {
         $email = '';
     }
     $globalConfig = SimpleSAML_Configuration::getInstance();
     $t = new SimpleSAML_XHTML_Template($globalConfig, 'core:no_state.tpl.php');
     /* Enable error reporting if we have a valid technical contact email. */
     if ($globalConfig->getString('technicalcontact_email', '*****@*****.**') !== '*****@*****.**') {
         /* Enable error reporting. */
         $baseurl = SimpleSAML_Utilities::getBaseURL();
         $t->data['errorReportAddress'] = $baseurl . 'errorreport.php';
         $t->data['reportId'] = $errorData['reportId'];
         $t->data['email'] = $email;
     }
     $t->show();
     exit;
 }
 /**
  * Apply filter to add the SchacHomeOrganization attribute.
  *
  * @param array &$request  The current request
  */
 public function process(&$request)
 {
     assert('is_array($request)');
     assert('array_key_exists("Attributes", $request)');
     $authModule = NULL;
     // Fetch Auth module
     if (array_key_exists("SimpleSAML_Auth_State.stage", $request)) {
         $authStage = implode(":", array_slice(explode(':', $request["SimpleSAML_Auth_State.stage"]), 0, -1));
         $authId = $authStage . ':AuthId';
         $authModule = $request[$authId];
     } else {
         if (isset($request['AuthnInstant']) && isset($request['Expire'])) {
             // Probably dealing with a cached response
             $cachedAuthModule = SimpleSAML_Session::getInstance()->getData(sspmod_multiauth_Auth_Source_MultiAuth::SESSION_SOURCE, 'multi');
             if ($cachedAuthModule) {
                 $authModule = $cachedAuthModule;
             }
         }
     }
     if (!isset($authModule)) {
         throw new Exception("Auth module not found?!?!");
     }
     $attributes =& $request['Attributes'];
     // Set or replace the schacHomeOrganization attribute
     if (array_key_exists($authModule, $this->map)) {
         $schacHomeOrganization = $this->map[$authModule];
         if (isset($schacHomeOrganization)) {
             $attributes["schacHomeOrganization"] = $schacHomeOrganization;
             return;
         }
     }
     if (array_key_exists(DEFAULT_SCHACHOMEORG, $this->map)) {
         throw new Exception("No default schacHomeOrganization?!?");
     }
     $attributes["schacHomeOrganization"] = $this->map[DEFAULT_SCHACHOMEORG];
 }
示例#21
0
#!/usr/bin/env php
<?php 
/*
 * This script can be used to generate metadata for simpleSAMLphp
 * based on an XML metadata file.
 */
/* This is the base directory of the simpleSAMLphp installation. */
$baseDir = dirname(dirname(dirname(dirname(__FILE__))));
/* Add library autoloader. */
require_once $baseDir . '/lib/_autoload.php';
SimpleSAML_Session::useTransientSession();
/* No need to try to create a session here. */
if (!SimpleSAML_Module::isModuleEnabled('metarefresh')) {
    echo "You need to enable the metarefresh module before this script can be used.\n";
    echo "You can enable it by running the following command:\n";
    echo '  echo >"' . $baseDir . '/modules/metarefresh/enable' . "\"\n";
    exit(1);
}
/* Initialize the configuration. */
SimpleSAML_Configuration::setConfigDir($baseDir . '/config');
/* $outputDir contains the directory we will store the generated metadata in. */
$outputDir = $baseDir . '/metadata-generated';
/* $toStdOut is a boolean telling us wheter we will print the output to stdout instead
 * of writing it to files in $outputDir.
 */
$toStdOut = FALSE;
/* $validateFingerprint contains the fingerprint of the certificate which should have been used
 * to sign the EntityDescriptor in the metadata, or NULL if fingerprint validation shouldn't be
 * done.
 */
$validateFingerprint = NULL;
<?php

/**
 * Show a warning to an user about the SP requesting SSO a short time after
 * doing it previously.
 *
 * @package SimpleSAMLphp
 */
if (!array_key_exists('StateId', $_REQUEST)) {
    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
}
$id = $_REQUEST['StateId'];
$state = SimpleSAML_Auth_State::loadState($id, 'core:short_sso_interval');
$session = SimpleSAML_Session::getSessionFromRequest();
if (array_key_exists('continue', $_REQUEST)) {
    // The user has pressed the continue/retry-button
    SimpleSAML_Auth_ProcessingChain::resumeProcessing($state);
}
$globalConfig = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($globalConfig, 'core:short_sso_interval.php');
$t->data['target'] = SimpleSAML\Module::getModuleURL('core/short_sso_interval.php');
$t->data['params'] = array('StateId' => $id);
$t->data['trackId'] = $session->getTrackID();
$t->show();
示例#23
0
文件: State.php 项目: hukumonline/yii
 /**
  * Delete state.
  *
  * This function deletes the given state to prevent the user from reusing it later.
  *
  * @param array &$state  The state which should be deleted.
  */
 public static function deleteState(&$state)
 {
     assert('is_array($state)');
     if (!array_key_exists(self::ID, $state)) {
         /* This state hasn't been saved. */
         return;
     }
     $session = SimpleSAML_Session::getInstance();
     $session->deleteData('SimpleSAML_Auth_State', $state[self::ID]);
 }
 /**
  * Tries to retrieve the configured auth data (see internal->authData) from
  * its' methods and make it availabe in the global context for later usage
  * by the configured methodSetupFile.
  */
 private function retrieveAuthData()
 {
     global $authData;
     $authData = array();
     $libName = $this->config['internal']['authLib'];
     $attributes = $this->config['internal']['authData'];
     $skipped = false;
     switch ($libName) {
         /*
          * SHIBBOLETH
          */
         case 'shibboleth':
             if ($this->config['debug']['logRawAuthLibAttibuteData']) {
                 wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . "Shibboleth:\n" . print_r($_SERVER, true));
             }
             foreach ($attributes as $attribute) {
                 if (isset($_SERVER[$attribute])) {
                     $authData[$attribute] = $_SERVER[$attribute];
                 } else {
                     $authData[$attribute] = '';
                 }
             }
             break;
             /*
              * SIMPLESAMLPHP
              */
         /*
          * SIMPLESAMLPHP
          */
         case 'simplesamlphp':
             $ssphpPath = $this->config['paths']['libs']['simplesamlphp'];
             if (file_exists($ssphpPath . "/www/_include.php")) {
                 // load simpleSAMLphp library
                 require_once $ssphpPath . "/www/_include.php";
                 // Load simpleSAMLphp configuration and session.
                 $config = SimpleSAML_Configuration::getInstance();
                 $session = SimpleSAML_Session::getInstance();
                 $ssphpAttrs = array();
                 if ($session->isValid('saml2')) {
                     // retrieve attributes
                     $ssphpAttrs = $session->getAttributes();
                     if ($this->config['debug']['logRawAuthLibAttibuteData']) {
                         wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . "SimpleSAMLphp:\n" . print_r($ssphpAttrs, true));
                     }
                 } else {
                     wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . "No valid session found.");
                 }
                 foreach ($attributes as $attribute) {
                     if (isset($ssphpAttrs["urn:mace:dir:attribute-def:" . $attribute][0])) {
                         $authData[$attribute] = $ssphpAttrs["urn:mace:dir:attribute-def:" . $attribute][0];
                     } else {
                         $authData[$attribute] = '';
                     }
                 }
             } else {
                 wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . "Could not load SimpleSAMLphp lib from '{$ssphpPath}'.");
             }
             break;
             /*
              * UNKNOWN/INVALID LIBRARY
              */
         /*
          * UNKNOWN/INVALID LIBRARY
          */
         default:
             wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . "Skipped unknown authentication library '{$libName}'.");
             $skipped = true;
             // set attributes to '' for the unknown lib
             foreach ($attributes as $attribute) {
                 $authData[$attribute] = '';
             }
     }
     if (!$skipped && $this->config['debug']['logRetrievedAttributeData']) {
         wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . "" . print_r($authData, true));
     }
 }
示例#25
0
 /**
  * Check whether the current user is admin.
  *
  * @return boolean True if the current user is an admin user, false otherwise.
  *
  * @author Olav Morken, UNINETT AS <*****@*****.**>
  */
 public static function isAdmin()
 {
     $session = \SimpleSAML_Session::getSessionFromRequest();
     return $session->isValid('admin') || $session->isValid('login-admin');
 }
示例#26
0
文件: State.php 项目: filonuse/fedlab
 /**
  * Delete state.
  *
  * This function deletes the given state to prevent the user from reusing it later.
  *
  * @param array &$state  The state which should be deleted.
  */
 public static function deleteState(&$state)
 {
     assert('is_array($state)');
     if (!array_key_exists(self::ID, $state)) {
         /* This state hasn't been saved. */
         return;
     }
     SimpleSAML_Logger::debug('Deleting state: ' . var_export($state[self::ID], TRUE));
     $session = SimpleSAML_Session::getInstance();
     $session->deleteData('SimpleSAML_Auth_State', $state[self::ID]);
 }
示例#27
0
 /**
  * Check for session cookie, and show missing-cookie page if it is missing.
  *
  * @param string|NULL $retryURL  The URL the user should access to retry the operation.
  */
 public static function checkCookie($retryURL = NULL)
 {
     assert('is_string($retryURL) || is_null($retryURL)');
     $session = SimpleSAML_Session::getSessionFromRequest();
     if ($session->hasSessionCookie()) {
         return;
     }
     /* We didn't have a session cookie. Redirect to the no-cookie page. */
     $url = SimpleSAML_Module::getModuleURL('core/no_cookie.php');
     if ($retryURL !== NULL) {
         $url = self::addURLParameter($url, array('retryURL' => $retryURL));
     }
     self::redirectTrustedURL($url);
 }
示例#28
0
<?php

require_once '../../www/_include.php';
$config = SimpleSAML_Configuration::getInstance();
$metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
$session = SimpleSAML_Session::getInstance();
$ldapconfigfile = $config->getBaseDir() . 'config/ldapmulti.php';
require_once $ldapconfigfile;
SimpleSAML_Logger::info('AUTH - ldap-multi: Accessing auth endpoint login-ldapmulti');
if (empty($session)) {
    SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOSESSION');
}
$error = null;
$attributes = array();
/* Load the RelayState argument. The RelayState argument contains the address
 * we should redirect the user to after a successful authentication.
 */
if (!array_key_exists('RelayState', $_REQUEST)) {
    SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE');
}
if (isset($_POST['username'])) {
    try {
        $ldapconfig = $ldapmulti[$_POST['org']];
        if ($ldapconfig['search.enable'] === TRUE) {
            if (!$ldap->bind($ldapconfig['search.username'], $ldapconfig['search.password'])) {
                throw new Exception('Error authenticating using search username & password.');
            }
            $dn = $ldap->searchfordn($ldapconfig['search.base'], $ldapconfig['search.attributes'], $_POST['username']);
        } else {
            $dn = str_replace('%username%', $_POST['username'], $ldapconfig['dnpattern']);
        }
示例#29
0
 /**
  * Handle a unsolicited login operations.
  *
  * This function creates a session from the received information. It
  * will then redirect to the given URL.
  *
  * This is used to handle IdP initiated SSO.
  *
  * @param string $authId The id of the authentication source that received
  * the request.
  * @param array $state A state array.
  * @param string $redirectTo The URL we should redirect the user to after
  * updating the session. The function will check if the URL is allowed, so
  * there is no need to manually check the URL on beforehand. Please refer
  * to the 'trusted.url.domains' configuration directive for more
  * information about allowing (or disallowing) URLs.
  */
 public static function handleUnsolicitedAuth($authId, array $state, $redirectTo)
 {
     assert('is_string($authId)');
     assert('is_string($redirectTo)');
     $session = SimpleSAML_Session::getSessionFromRequest();
     $session->doLogin($authId, self::extractPersistentAuthState($state));
     SimpleSAML_Utilities::redirectUntrustedURL($redirectTo);
 }
示例#30
0
 /**
  * Retrieve all authentication data.
  *
  * @return array|NULL  All persistent authentication data, or NULL if we aren't authenticated.
  */
 public function getAuthDataArray()
 {
     if (!$this->isAuthenticated()) {
         return NULL;
     }
     $session = SimpleSAML_Session::getSessionFromRequest();
     return $session->getAuthState($this->authSource);
 }