简体   繁体   中英

CakePhp 3 keep auth session

I'm trying to log user automatically in cakephp 3 after closed the browser. I follow this post but it doesn't change anything. The session with "my-app" name exist but users doesn't automatically log.

My code in AppController:

$this->loadComponent('Auth', [
        'loginRedirect' => [
            'controller' => 'Usagers',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Admin',
            'action' => 'index'
        ],
        'storage' => [
            'className' => 'Session',
            'key' => 'Auth.User',
        ],
    ]);

my code in usersController :

public function login()
{
    $this->viewBuilder()->setLayout('ajax');
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Invalid username or password, try again'));
    }
}

I don't know why my session is not keeped.

Do you have any suggestions ?

Using security and Csrf protection?

If so, you will need to set expiration time in both. You can increase sesstion time, but the Csrf cookie will be gone when browser close as default.

Example for 7days expiration using CakePHP 3

in app.php:

'Session' => [
    'defaults' => 'php',
    'cookie' => 'CookieName',
    'ini' => [
        'session.cookie_lifetime' => 604800 // 7 days
    ],
    'timeout' => 10080 // 7 days
],

in AppController.php

$this->loadComponent('Csrf',['secure'=>true,'expiry'=> strtotime("+7 day")]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM