The Method of Realizing Single Sign on in Yii2

  • 2021-09-12 00:32:14
  • OfStack

This article introduces the method of realizing single sign-on in Yii2 and shares it with you as follows:

Modification/common/config/main. php

1. Add the following code to the config header


<?php
// Session  Cross-domain 
$host = explode('.', $_SERVER["HTTP_HOST"]);
if (count($host) > 2) {
  define('DOMAIN', $host[1] . '.' . $host[2]);
} else {
  define('DOMAIN', $host[0] . '.' . $host[1]);
}

2. Add to the components configuration of config


<?php
'user' => [
  'identityClass' => 'common\models\User',
  'enableAutoLogin' => true,
  'identityCookie' => ['name' => '_identity', 'httpOnly' => true, 'domain' => '.'.DOMAIN],
],
'session' => [
  'cookieParams' => ['domain' => '.'.DOMAIN, 'lifetime' => 0],
  'timeout' => 3600,
],

3. Use in controller


<?php
// Settings 
Yii::$app->session['var']='value';
// Use 
echo Yii::$app->session['var'];
// Remove 
unset(Yii::$app->session['var']);

STEP 4 Test

4.1 www. aaa. com login

4.2 www. bbb. com session still works.


Related articles: