Yii 2.0: Configuring different sessions for backend and frontend in Yii advanced app

31 followers

Problem Statement

After you have setup your Yii2 advanced application, you now have setup your user authentication for both frontend and backend. However, if you have first logged into frontend, and try to access backend from the same client machine, you see no login screen, but find yourself automatically logged in.

Your need: You require that for shared machines, the user is authenticated again for a backend access again, if someone is logged in from frontend and vice versa.

Reasoning

You by default have enabled cookie based login when you have setup the yii\user component. Hence the session cookie by default is same for the entire domain.

Solutions

Your solutions are a couple of options:

Option 1: Disable Autologin

You can disable cookie based login (though not desired by many). But this will require users to login each time in the client.

'user' => [
      'identityClass' => 'app\models\User',
      'enableAutoLogin' => false, // disable all cookie based authentication
]

However, if you require cookies for ideal user experience, you need to follow the approach below.

Option 2: Configure Identity Cookie

You can configure different identity cookies for your user component for frontend and backend app. Note the unique name property in identityCookie.

Backend Config

// in backend/config/main.php
'user' => [
      'identityClass' => 'app\models\User',
      'enableAutoLogin' => true,
      'identityCookie' => [
          'name' => '_backendUser', // unique for backend
          'path'=>'/advanced/backend/web'  // correct path for the backend app.
      ]
  ],

Frontend Config

// in frontend/config/main.php
'user' => [
      'identityClass' => 'app\models\User',
      'enableAutoLogin' => true,
      'identityCookie' => [
          'name' => '_frontendUser', // unique for frontend
          'path'=>'/advanced/frontend'  // correct path for the frontend app.
      ]
  ],

This should now allow you to have cookie based login, but different authentication sessions for frontend and backend.

Be the first person to leave a comment

Please to leave your comment.

Write new article