I got problem with Zend 2 session
When I 'quickly' double click 'Enter' in _POST form ( twice submit form before first respond) session is destroyed. When I submit 'in normal speed' all is OK.
My session configuration is exact copy of this http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
only difference is
'session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => 'myapp',
'remember_me_seconds' => 3600, //60 min session
'use_cookies' => true,
// 'cookie_httponly' => true, -> not working with Zfc-user subdomain
'cookie_domain'=>'domain.com',
),
),
'storage' => 'Zend\Session\Storage\SessionArrayStorage',
'validators' => array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
),
),
In controler I have:
const NAMESPACE_REGORG = 'initialized';
protected $_sessionRegContainer;
public function packageAction() {
//check if user login and redirect
if ($this->zfcUserAuthentication()->hasIdentity()) {
//some staff here
}
//save value to session
$package = $this->getEvent()->getRouteMatch()->getParam('id');
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
$this->_sessionRegContainer->package = $package;
return $this->redirect()->toRoute(static::ROUTE_LOGIN);
}
public function loginAction() {
//restore session
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
//create form staff.. if submited by double click session is loosing
//value of $this->_sessionRegContainer->package
}
Page use Doctrine 2 ORM , Zfc-user module for authentication and sub-domain for all Zend 2 related content - main domain.com is static html.
It is worth to mention that when I use simple new Container() session with out all setup from Zend page - session work fine with 'double click' but zfc-user stop to work :(
Any idea why session is destroyed? Any help will be appreciated
I sorted it by removing
$session->start();
$session->rememberMe();
from Zend 2 exmple setup -> http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
Double click session destroy ended (fixed).
ps. It look like they already remove rememberMe() from exmple.
Thanks for all help!
Related
I have time in seconds when the session should end. If the user has not selected the checkbox "remember_me" - the session will last 2 hours. When the checkbox is selected - should last - 48 hours. I have a loginСontroller, where I react - to the login result and if the validation is successful and checkbox = "on" you need to change the session time. I tried to change by looking at the documentation, and spent a lot of time looking for a solution. Maybe someone can help me. Thank you very much in advance[enter image description here]
here is my file config/app.php
'Session' => [
'defaults' => 'php',
'ini' => [
'session.cookie_lifetime' => 7200,
]
],
and here is my loginController
`public function index()
{
$this->viewBuilder()->setLayout('main');
$this->set("title", "");
$this->set("description", "description");
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
if ($this->request->getData('remember') == 'on') {
///// the solution should be here
}
$redirect = [
'controller' => 'Main',
'action' => 'index',
];
return $this->redirect($redirect);
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->saved_error(__('Invalid email or password'));
}
}`
You most likely shouldn't do it that way, your controller code shouldn't have to know about such details if it can be avoided.
The authentication plugin ships with a cookie based authenticator that you can use in addition to the session authenticator, that way you can extend authentication beyond the default session lifetime, I'd suggest that you look into that instead.
$service->loadAuthenticator('Authentication.Cookie', [
'fields' => $fields,
'loginUrl' => $loginUrl,
'cookie' => [
// cookie expires in 2 days from now
'expires' => \Cake\Chronos\Chronos::now()->addDays(2)
],
]);
By default the authenticator looks up a field named remember_me, so either rename that in your template, like:
echo $this->Form->control('remember_me', ['type' => 'checkbox']);
or configure the authenticator's rememberMeField option with the custom field name that you're using in your form.
See also
Authentication Cookbook > Authenticators > Cookie Authenticator
In ZF3, I'm initializing my session as following:
config/autoload/global.php
'session_config' => [
'name' => 'gintra3',
'cookie_lifetime' => 60*60*1,
'gc_maxlifetime' => 60*60*24*30,
],
'session_storage' => [
'type' => Zend\Session\Storage\ArrayStorage::class,
],
'session_manager' => [
'storage' => Zend\Session\Storage\SessionArrayStorage::class,
'validators' => [
Zend\Session\Validator\RemoteAddr::class,
Zend\Session\Validator\HttpUserAgent::class,
],
],
module/Application/Module.php
$sessionManager = $e->getApplication()->getServiceManager()->get(SessionManager::class);
$sessionTableGateway = new TableGateway('session',$e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter'));
$sessionSaveHandler = new DbTableGateway($sessionTableGateway,new DbTableGatewayOptions());
$sessionManager->setSaveHandler($sessionSaveHandler);
Now, when I'm storing data like this on page 1:
$sessionC = new Container('test');
$sessionC->testVariable = "helloWorld";
And retrieve it on page 2 like this:
$sessionC = new Container('test');
Debug::dump($sessionC->testVariable);
I get an output on page 2 like this:
vendor/zendframework/zend-debug/src/Debug.php:97:null
When I check the database table, the 'data' column of the corresponding session_id contains "helloWorld" after loading page 1. After loading page 2, it does not contain "helloWorld" anymore.
If I comment out all session-related lines in Module.php, a PHPSESSID cookie is created on page load and session data saving and storing works fine now.
It does not matter if I use DbTableGateway as a save_handler or just use standard save_handler. The problem occurs in both cases.
When using my individual session storage, also FlashMessenger and Csrf-Form-Validation stop working due to the same mechanism of loosing all session data on page load.
Where is my problem? What am I overseeing?
Thanks a lot for some ideas.
Using Yii2 framework:
The code below creates an endless loop.
Can anyone please explain how I make the session data persist on redirect ?
I have checked and there is not data being transferred, but the session data is set inside searchuser correctly.
public function actionSearchUser()
{
$session = \Yii::$app->session;
$session->open();
$session->set('admin.currentuser.id', "This worked out ok");
return $this->redirect(['site/modify-user']);
}
public function actionModifyUser()
{
$session = \Yii::$app->session;
$session->open();
if( !($session->has('admin.currentuser.id')) )
{
return $this->redirect(['site/search-user']);
}
else return $this->render('modifyUser');
}
And here is where I setup my session:
'session'=>array(
'class' => 'yii\web\Session',
'name' => 'SESSIONNAME',
'timeout' => 86400,
'savePath' => '/path/to/sessions',
'useCookies' => true,
'cookieParams' => array(
'lifetime' => 86400,
'path' => '/',
'domain' => 'localhost',
),
),
My problem was the domain (I know, I'm stupid).
I have a custom domain (n099y.local) so I needed to change the cookie domain from localhost to n099y.local and everything was fine.
It was showing all the correct session data on the page until I went to another page when the data was again missing because the cookie domain did not match the domain I was on.
I have a subnav bar in my module created from a view partial via a helper.
Here is the config in module.config.php:
'navigation' => array(
'default' => array(
array(
'label' => 'Create',
'route' => 'mymodule\Create',
),
array(
'label' => 'View',
'route' => 'mymodule\view',
),
array(
'label' => 'Search',
'route' => 'mymodule\search',
),
array(
'label' => 'Log Off',
'route' => 'mymodule\logoff',
),
),
),
);
So here is my problem, I don't just want to redirect the user to the login page, I want to clear their session and THEN redirect them to the login page. I also don't want to have the login page just clear the session whenever a user navigates to it (in case they logged in and clicked the back button accidentally).
So what is the best way to handle this with my current config? I was thinking I could have my view helper that renders the partial set a flag in the session which the logon page would read and act accordingly- it would check for a "logoffButtonPress" flag in the session or something. But is it appropriate to do something like this in a view helper? Is this even possible in a view helper?
Why not just have the button target a logoutAction?
I'm using BjyAuthorise and ZfcUser modules but the process of clearing the session and redirecting is the same.
LoginController
public function logoutAction()
{
$this->authService->logout();
$redirect = $this->params('redirect', false);
if ($redirect) {
return $this->redirect()->toUrl($redirect);
}
return $this->redirect()->toRoute(
$this->config->getLogoutRedirectRoute()
);
}
AuthService
public function logout()
{
$adapter = $this->authService->getAdapter();
$adapter->resetAdapters();
$adapter->logoutAdapters();
$this->authService->clearIdentity();
}
Like Alex says, that is the way to do that.
This code is correct
array(
'label' => 'Log Off',
'route' => 'mymodule\logoff',
),
So, you need to set a logoff action to 'mymodule\logoff' route, clear the session and redirect the user to login or home or what you want.
On the login action you dont need to clear session.
I have the following config in my AppController:
public $components = array(
'Session',
'Security' => array(
'blackHoleCallback' => 'blackHole',
'csrfExpires' => '+1 hour',
'csrfUseOnce' => false
)
);
My dev version of the blackHole callback function:
public function blackHole($type) {
$this->Session->setFlash(
sprintf('Is session valid: %d, Security issue type: %s',
$this->Session->valid(), $type));
}
For testing purposes my session config stored in the core.php looks like this:
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 1 // 1 minute
)
);
Now, when I login, go to a page with some form and submit the form after 1 minute my session expires (as expected) but $this->Session->valid() returns true in my blackHole callback (btw: $type value is 'csrf'). Why Cake claims session is valid when it isn't?
I am using CakePHP v.2.4.3.