Skip to content

Session validation failed #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
YuChuanchun opened this issue Aug 8, 2017 · 7 comments
Closed

Session validation failed #25

YuChuanchun opened this issue Aug 8, 2017 · 7 comments

Comments

@YuChuanchun
Copy link

YuChuanchun commented Aug 8, 2017

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

@SidiaDevelopment
Copy link

SidiaDevelopment commented Aug 15, 2017

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

@Mecanik
Copy link

Mecanik commented May 1, 2018

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
    }

@olegkrivtsov
Copy link
Owner

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

@olegkrivtsov
Copy link
Owner

Thanks @Mecanik, used your code. Fixed.

olegkrivtsov added a commit that referenced this issue May 2, 2018
@nanguisamuel
Copy link

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.

@Mecanik
Copy link

Mecanik commented Apr 27, 2020

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.

@nanguisamuel
Copy link

nanguisamuel commented Apr 27, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants