Cakephp 3:跨多个应用程序的共享数据库会话

I have two Cakephp 3 apps that save their sessions on the same "sessions" table on the same database. I've been trying to set it up so that they share the same sessions, so that when I'm logged in to either one, I'm automatically logged in to the other.

I have this in both of their app.php files:

'Session' => [
    'defaults' => 'database'
],

And this is the "sessions" table they're both using: enter image description here

Logging into both results in them having different entries in the table.

Thanks in advance for any suggestions.

While this could theoretically be possible, note that since Database-stored sessions aren't thread locked multiple apps could be writing to the session at the same time. Lots of data is stored in the session data (all the Auth information) so you'll need to be careful to ensure user data is handled uniformly across all apps.

But generally you'll want to create a new Datasource that will contain the shared "sessions" table (ex. named shared_sessions, in app.php:

'Datasources'    => [ 
    'shared_sessions'   => [
        'className'        => 'Cake\Database\Connection',
        'driver'           => 'Cake\Database\Driver\Mysql',
        'persistent'       => false,
        'host'             => 'localhost',
        'port'             => '3306',
        'username'         => 'sessions_user',
        'password'         => '*******',
        'database'         => 'SHARED_SESSIONS',
        'timezone'         => 'UTC'
    ],

If you don't already have a SessionsTable, create it and specify the alternative connection information:

class SessionsTable extends Table
{
    /**
     * @return string
     */
    public static function defaultConnectionName()
    {
        return 'shared_sessions';
    }

    ....

You may still need to handle differences in other Auth data depending on what each app does to set/manipulate it, you may need to do some centralized storage in the shared database, but also store Auth data on an app level, using a Custom Storage Handler.

See: