Skip to content

Session validation failed #25

Description

@YuChuanchun

(userdemo) when i press F12 in chrome, then refresh the page, it report "Session validation failed" Exception.

Activity

  1. SidiaDevelopment commented on Aug 15, 2017

    @SidiaDevelopment

    Do you have user agent spoofing (mobile spoofing) active? The session gets validated by user agent

  2. Mecanik commented on May 1, 2018

    @Mecanik

    This is because you have in your config:

    		'session_manager' => [
    				// Session validators (used for security).
    				'validators' => [
    						RemoteAddr::class,
    						HttpUserAgent::class,
    				]
    		],
    

    Comment out "HttpUserAgent::class" and you will get rid of the error, because there is a bug.

    Alternatevely use my fix:

    Module.php

     /**
         * This method is called once the MVC bootstrapping is complete and allows
         * to register event listeners. 
         */
        public function onBootstrap(MvcEvent $event)
        {
    $sessionManager = $event->getApplication()->getServiceManager()->get('Zend\Session\SessionManager');
            
            $this->forgetInvalidSession($sessionManager);
        }
    
        protected function forgetInvalidSession($sessionManager) {
        	try {
        		$sessionManager->start();
        		return;
        	} catch (\Exception $e) {
        	}
        	/**
        	 * Session validation failed: toast it and carry on.
        	 */
        	// @codeCoverageIgnoreStart
        	session_unset();
        	// @codeCoverageIgnoreEnd
        }
    
  3. olegkrivtsov commented on May 1, 2018

    @olegkrivtsov
    Owner

    Seems like try/catch handler is really required here: zendframework/zendframework#6390

  4. olegkrivtsov commented on May 2, 2018

    @olegkrivtsov
    Owner

    Thanks @Mecanik, used your code. Fixed.

  5. added a commit that references this issue on May 2, 2018
  6. nanguisamuel commented on Apr 27, 2020

    @nanguisamuel

    Hi @olegkrivtsov ,
    I use yout tuto for my personnal project. But I stuck on one point :

    I'm costumizing Laminas Skeleton and adding link (Fr|En) for translation. When clicking on the link I call an action wich add a variable (containing the selected language) in session and then reload the page to apply changes. The lanaguage variable in session is correctly set but when the page is reloaded it is removed and I do not know Why : Here is my module file :

    
    <?php
    
    /**
     * @see       https://github.com/laminas/laminas-mvc-skeleton for the canonical source repository
     * @copyright https://github.com/laminas/laminas-mvc-skeleton/blob/master/COPYRIGHT.md
     * @license   https://github.com/laminas/laminas-mvc-skeleton/blob/master/LICENSE.md New BSD License
     */
    
    declare(strict_types=1);
    
    namespace Application;
    
    use Laminas\Mvc\MvcEvent;
    use Laminas\Mvc\Controller\AbstractActionController;
    use Application\Service\AuthManager;
    use Application\Controller\AuthController;
    
    use Laminas\Session\SessionManager;
    
    class Module
    {
        public function getConfig() : array
        {
            return include __DIR__ . '/../config/module.config.php';
        }
    
    
        public function onBootstrap(MvcEvent $event){
            // Au demarrage, on va initialiser tous nos hiahi truc pour chose ici 
            // Get event manager.
            $eventManager = $event->getApplication()->getEventManager();
            $sharedEventManager = $eventManager->getSharedManager();                
    
            // Register the event listener method. 
            $sharedEventManager->attach(AbstractActionController::class, 
                    MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100);
    
    
    
    
    
            $serviceManager = $event->getApplication()->getServiceManager();
            $sessionManager = $serviceManager->get(SessionManager::class);   
    
            $this->forgetInvalidSession($sessionManager);
    
    
            // Get language settings from session.
            $container = $serviceManager->get('I18nSessionContainer');
    
            $languageId = 'en_US';
            if (isset($container->languageId)){
                $languageId = $container->languageId;            
            }
    
            var_dump($container->languageId);
    
            \Locale::setDefault($languageId);
    
            $translator = $serviceManager->get('translator');
            $translator->addTranslationFile(
                'ini',                
                __DIR__ . '/../../../data/translations/'.$languageId.'.ini',
                'default',
                $languageId
            );
    
    
            $translator->addTranslationFilePattern(
                'ini',
                __DIR__ . '/../../../data/translations',
                '%s.ini',
                'default'
            );
    
    
            //\Laminas\Validator\AbstractValidator::setDefaultTranslator(new \Laminas\I18n\Translator\Translator($translator));
    
    
            //$this->forgetInvalidSession($sessionManager);
        }
    
        protected function forgetInvalidSession($sessionManager) 
        {
            try {
                $sessionManager->start();                    
                return;
            } catch (\Exception $e) {
            }
            /**
             * Session validation failed: toast it and carry on.
             */
            // @codeCoverageIgnoreStart
            //session_unset();
            // @codeCoverageIgnoreEnd
        }
    
        public function onDispatch(MvcEvent $event){       
            $controller = $event->getTarget();
            $controllerName = $event->getRouteMatch()->getParam('controller', null);       
            $actionName = $event->getRouteMatch()->getParam('action', null);        
    
            // Convert dash-style action name to camel-case. Je pense pas avoir besoin de celui la.
            $actionName = str_replace('-', '', lcfirst(ucwords($actionName, '-')));  
    
    
    
            // Get the instance of AuthManager service.
            $authManager = $event->getApplication()->getServiceManager()->get(AuthManager::class);
    
            // Execute the access filter on every controller except AuthController
            // (to avoid infinite redirect).       
            if ($controllerName!=AuthController::class && !$authManager->filterAccess($controllerName, $actionName)) {            
                return $controller->redirect()->toRoute('connexion'); // La route qui a ete definie dans le fichier de config           
            }
    
    
        }
    
    }
    

    My Controller and action for switching language here :

    <?php
    namespace Commun\Controller;
    use Commun\Controller\NslabsAbstractController;
    class LocaleController extends NslabsAbstractController
    {
    
        public function switchLocaleAction()
        {        
            $locale = $this->post['locale'];                        
            if (empty($locale)) {
                $locale = 'fr';
            }
    
            $lang = $locale;
    
    
            switch ($lang) {
                case 'fr':
                    $this->sessionManager->i18nSessionContainer->languageId = 'fr_FR';                   
                    break;
                case 'en':
                    $this->sessionManager->i18nSessionContainer->languageId = 'en_US';                 
                    break;
                default :
                    $this->sessionManager->i18nSessionContainer->languageId = 'fr_FR';
            }
    
            return new \Laminas\Http\Response();
        }
    
    
    }
    

    I have to say that all my controllers extends the AbstractActionController in where I have added the ServiceManager and Session Manager as construct params.

    Any help would be really appreciated.

  7. Mecanik commented on Apr 27, 2020

    @Mecanik

    I recommend you to change language in "onRoute" rather than using session. If you really want to use sessions, there more that you must add/do than what you have.

  8. nanguisamuel commented on Apr 27, 2020

    @nanguisamuel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions