Automagically Log into Multiple Domains in Yii2 - php

I have a site with a root domain and several sub domains, each a separate yii2 module. At the moment I have to log into each sub domain individually. I want to be able to log into the root directory and then be automatically logged into each of the sub domains. There are a few pages here and there on the web about achieving this but nothing that works.
at the moment I have the same setup in both main.php config files (i.e. the root domain and one of the sub domains that I am testing with)
'components' => [
'request' => [
'enableCookieValidation' => true,
'enableCsrfValidation' => true,
'cookieValidationKey' => 'XXXXXXX',
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_myapp',
'httpOnly' => true,
'path' => '/',
]
],
'session' => [
'name' => 'MYAPPSESSID',
'cookieParams' => [
'path' => '/',
],
],
When inspecting my cookies in Chrome after logging in with setup I see two cookies, one for the main site and one for the sub domain, they are both called MYAPPSESSID, and both containing different 'keys' that presumably hook up to the user info set on the PHP session. I get that these two cookies should be one cookie so that both domains hook up to the session user object - but I;ve tried all the different settings I can think of and can't get this to work.

To be able to log on all subdomains, use the following config:
'components' => [
'session' => [
// ...
'cookieParams' => [
'path' => '/',
'domain' => ".domain.com",
],
],
'user' => [
// ...
'identityCookie' => [
'name' => '_identity',
'path' => '/',
'domain' => ".domain.com",
],
],
'request' => [
// ...
'csrfCookie' => [
'name' => '_csrf',
'path' => '/',
'domain' => ".domain.com",
],
],
],

I figured this out in the end. The session->cookieParams needs a 'domain' set on both main.php config files, which is the top level domain name prefixed with a '.'. I did try this but the cookies were'n't being generated, and it turned out that it was because my local domains that I set in Mamp Pro were not formatted in a way that the cookies were expecting them. So my app was at http://myapp, and http://subdomain.myapp. It turns out that the cookie domain setting requires a top level domain (like .com). So I changed my hosts to http://myapp.local and http://subdomain.myapp.local. Then I set the cookie domains to .myapp.local and it worked.
here's my new config, which is on both the root domain and the sub domain. The user->identityCookie settings above turned out to be unnecessary btw.
'components' => [
'request' => [
'enableCookieValidation' => true,
'enableCsrfValidation' => true,
'cookieValidationKey' => 'XXXXXXX',
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'common\models\User',
'enableAutoLogin' => true
],
'session' => [
'name' => 'MYAPPSESSID',
'cookieParams' => [
'path' => '/',
'domain' => '.myapp.local'
],
],

Related

Facing issue with identity object after login while using Multiple User Identity Class in Yii2 Advanced

I have setup/created 2 user identity classes for 2 different login under config/main.php components:
'user' => [
'class'=>'yii\web\User',
'identityClass' => 'frontend\models\CustomerUser',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['customer/login'],
'identityCookie' => [
'name' => '_panelCustomer',
'httpOnly' => true,
],
],
'franchise'=>[
'class'=>'yii\web\Franchise',
'identityClass' => 'frontend\models\FranchiseUser',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['franchise/login'],
'identityCookie' => [
'name' => '_panelFranchise',
'httpOnly' => true,
],
],
When i logged in using franchise, after login if i check Yii::$app->user->identity it gives me details for 1st record in database (vice versa for user login). I want to get null for Yii::$app->user->identity when i logged in as franchise.
When we add multiple identity into configuration, please change its idParam parameter.
'user' => [
'class'=>'yii\web\User',
'identityClass' => 'frontend\models\CustomerUser',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['customer/login'],
'idParam' => '__cid',
'identityCookie' => [
'name' => '_panelCustomer',
'httpOnly' => true,
],
],
'franchise' => [
'class'=>'yii\web\User',
'identityClass' => 'frontend\models\FranchiseUser',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['franchise/login'],
'idParam' => '__fid',
'identityCookie' => [
'name' => '_panelFranchise',
'httpOnly' => true,
],
],
You select 1'st components of the user, Check with this:
$user = Yii::$app->get('franchise');
$user->identity
But, The best solution for this purpose using an advanced template with a separated configuration for users.
https://github.com/yiisoft/yii2-app-advanced
Or you can use module and change configuration in runtime, Inside of Module.php:
public function init() {
parent::init();
Yii::$app->setComponents([
'user' => [
'class'=>'yii\web\Franchise',
'identityClass' => 'frontend\models\FranchiseUser',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['franchise/login'],
'identityCookie' => [
'name' => '_panelFranchise',
'httpOnly' => true,
],
],
]);
}
And repeat this for another user module.

Yii2 changing session name for dividing frontend & backend user login not working

Actually, I am trying to change the session "PHPSESSID" to "PHPFRONTSESSID" and "PHPBACKSESSID" respectively for dividing login for users frontend and backend. I have hosted it in GODADDY shared hosting and it was working fine before but not working now. It is not changing the session name it is using same name "PHPSESSID" for frontend and backend.
frontend/config/main.php
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
]
],
'session' => [
'name' => 'PHPFRONTSESSID',
'savePath' => __DIR__ . '/../runtime', // a temporary folder on frontend
],
Chnage in your config file and check it
Cookie Backend
'identityCookie' => [
'name' => '_backendIdentity',
'path'=>'/admin',
'httpOnly' => true,
],
Cookie Frontend
'identityCookie' => [
'name' => '_frontendIdentity',
'path'=>'/',
'httpOnly' => true,
],
Session Backend
'session' => [
'name' => 'session_backend'
],
Session Frontend
'session' => [
'name' => 'session_frontend'
],

Different Session for Cakephp Prefix

I'm strangling with a simple matter :
How to tell Cake to use a different Session configuration for different prefix (routes).
I have the main domain www.domain.tdl and I don't want the prefix couriers (www.domain.tdl/couriers) to use the same Session configuration to avoid Authentification problems : the main domain and prefix use different Authentification configurations.
So, in my App.php, the Session config is :
'Session' => [
'defaults' => 'cake',
'timeout' => 24 * 60, //in minutes,
'cookie' => 'app_bo',
// "cookiePath" => "/mrbo", (tried with or without)
'ini' => [
"session.name" => "MR_BO",
]
],
And I thought I could change the config in the AppController of the prefix :
src/Controller/Couriers/AppController.php
Configure::write('Session', [
'defaults' => 'cake',
'timeout' => 24 * 60, //in minutes,
'cookie' => 'app_courier',
"cookiePath" => "/mrcourier",
'ini' => [
"session.name" => "MR_COURIER",
]
]);
ini_set('session.cookie_name', 'app_courier');
ini_set('session.cookie_path', '/mrcourier');
ini_set('session.name', 'MR_COURIER');
Using only Configure::write did not work, that's why I added ini_set (seems like it update only internal CakePhp configuration).
By doing so, its works and not works. Indeed, I see that the domain and the prefix don't use the same, but when I tried to log in in the prefix page, nothing, it redirect to itself.
I think it's because CakePHP use Session internally before my settings in the prefix AppController.
EDIT
Here is the Auth component loading : (the one for the prefix is quit the same, only the controller model/controller change)
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'authenticate' => [
'Custom' => [
'passwordHasher' => [
'className' => 'Legacy',
],
'userModel' => 'Establishments',
'fields' => array('username' => 'login', 'password' => 'password'),
"salt" => "salt" // Relative field for SALT
],
],
'loginAction' => [
'controller' => 'establishments',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'pages',
'action' => 'dashboard'
],
'logoutRedirect' => [
'controller' => 'establishments',
'action' => 'login',
]
]);
In your auth configuration, use storage param to change Session settings. Use different key for each configuration
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'storage' => ['className' => 'Session', 'key' => 'Auth.Admin'],
/* ... */
]
);

How to save session in redis with cakephp 3.0?

Hello guy's I newbie in cakephp 3.0. I know little bit cakephp 2.0. I configured my redis with cakephp 2.0 with this help of url But I don't know how to configure in cakephp 3.0 please help me
Since Cakephp 4 is out, I am currently studying it (which seems exists in Cakphp 3 as well) and seems like there is a way to do it. Not tested yet.
Following this: https://book.cakephp.org/4/en/development/sessions.html#cache-sessions
app.php
'Session' => [
'defaults' => 'cache', //Use the Cache class to save session
'handler' => [
'config' => 'session'
]
],
Following this link: https://book.cakephp.org/4/en/core-libraries/caching.html#redisengine-options
app.php
/*
* Configure the cache adapters.
*/
'Cache' => [
'session' => [
'className' => RedisEngine::class,
//`port` The port your Redis server is running on.
//`host` The host your Redis server is running on.
//`database` The database number to use for connection.
//`password` Redis server password.
//`persistent` Should a persistent connection be made to Redis.
//`timeout` Connection timeout for Redis.
//`unix_socket` Path to a unix socket for Redist.
],
],
I am going to test this out later on and make update if needed, but it really seems promising.
Update 2020-05-20: Tested, it work fine
You would set your session to use cache sessions inside the app.php file:
'Session' => [
'defaults' => 'cache'
]
Then, you would set your cache to redis:
'Cache' => [
'default' => [
'className' => 'Redis',
],
]
In vendor\cakephp\cakephp\src\Network\Session.php
you can see the default type of session.
They are listed as php, cake,cache , database.
$defaults = [
'php' => [
'cookie' => 'CAKEPHP',
'ini' => [
'session.use_trans_sid' => 0,
]
],
'cake' => [
'cookie' => 'CAKEPHP',
'ini' => [
'session.use_trans_sid' => 0,
'session.serialize_handler' => 'php',
'session.use_cookies' => 1,
'session.save_path' => TMP . 'sessions',
'session.save_handler' => 'files'
]
],
'cache' => [
'cookie' => 'CAKEPHP',
'ini' => [
'session.use_trans_sid' => 0,
'session.use_cookies' => 1,
'session.save_handler' => 'user',
],
'handler' => [
'engine' => 'CacheSession',
'config' => 'default'
]
],
'database' => [
'cookie' => 'CAKEPHP',
'ini' => [
'session.use_trans_sid' => 0,
'session.use_cookies' => 1,
'session.save_handler' => 'user',
'session.serialize_handler' => 'php',
],
'handler' => [
'engine' => 'DatabaseSession'
]
]
]
Here is cache using default config of Cache. Maybe you want to use defualt as a File Cache.
In app.php
create a new cache config
'redis' => [
'className' => 'Redis',
'server'=>'127.0.0.1',
'port'=>6379
],
Then you can use your new cache config here.
'Session' => [
'cookie' => 'herewego',
'ini' => [
'session.use_trans_sid' => 0,
'session.use_cookies' => 1,
'session.save_handler' => 'user',
],
'handler' => [
'engine' => 'CacheSession',
'config' => 'redis'
]
],

Yii2: messed up data for separate sessions for frontend and backend

I am logged in on backend, but for some reason, the data is loaded from the user model not from admin model;
The admins have theyr own db table and the users have theyr owndb table;
The connection did not switched the db tables;
By using the admin id it loads the user data with the same id;
I use this config on frontend:
'components' => [
'session' => [
'name' => 'session_frontend',
],
'user' => [
// 'stateKeyPrefix' => 'frontend_stateKeyPrefix',
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
and this config for backend:
'components' => [
'session' => [
'name' => 'session_backend',
],
'user' => [
// 'stateKeyPrefix' => 'backend_stateKeyPrefix',
'identityClass' => 'common\models\Admin',
'enableAutoLogin' => true,
],
I actually assumed the stateKeyPrefix you added as a comment would indeed solve the problem, but that only works for 1.x it seems.
For 2.x the solution is a bit different:
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'idParam' => 'frontend__id'
],
You can leave one on __id or change both, it's however you want.

Categories