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.
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.
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 & Session ¶
You can configure different identity cookies and sessions 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'=>'/backend/web' // correct path for the backend app. ] ], 'session' => [ 'name' => '_backendSessionId', // unique for backend 'savePath' => __DIR__ . '/../runtime', // a temporary folder on backend ],
Frontend Config ¶
// in frontend/config/main.php 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, 'identityCookie' => [ 'name' => '_frontendUser', // unique for frontend 'path'=>'/frontend/web' // correct path for the frontend app. ] ], 'session' => [ 'name' => '_frontendSessionId', // unique for frontend 'savePath' => __DIR__ . '/../runtime', // a temporary folder on frontend ],
This should now allow you to have cookie based login, but different authentication sessions for frontend and backend.
The sessions are same
Thanks for this article. By this the enableAutoLogin identification cookie is separate for frontend and backend, which is useful.
Still, when either frontend or backend is signed in and we open the other, it shows automatically signed in because the session cookie is same, PHPSESSID.
So we are unable to maintain separate sessions. Do you have any method to change the name of PHPSESSID cookie so that two separate sessions can be maintained?
Got a solution. Add the session component in the configuration file.
A new wiki Added
Sessions have been updated
Session configuration has been updated.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.