Fully parse Yii2 cross-domain SSO login logic

Source: Internet
Author: User

Briefly

This article is a comprehensive logical analysis of how YII2 realizes SSO. In fact, I have written two articles about SSO login implementation and further optimization, including this article is also introduced YII2 SSO login, gradually optimize the continuous summary and share, the purpose is to YII2 SSO login function as far as possible to achieve the ultimate, Think of the problem from the point of view of the flexibility of program development and stifle all potential limitations in the cradle.

Implementation steps

1. The commonconfigmain.php file is configured as follows:

 [' User ' = [' identityclass ' = ' login\models\user ', ' Enableautologin ' =&G T True, ' identitycookie ' = [' name ' = ' = ' _identity ', ' httponly ' = ' = ', ' domain ' = '. '. DOMAIN],//' returnUrl ' = '/'. Domain_home,], ' session ' = [' cookieparams ' and ' = ' domain ' = '. '. D Omain, ' lifetime ' = 0], ' timeout ' = 24*3600*30,],

2. Create a new login module and open commonconfigbootstrap.php to add a code like this:

Yii::setalias (' Login ', dirname (dirname (__dir__)). '/login '); Add a custom directory structure

3, modify the Urlmanager in loginconfigmain.php, change to the following like this:

        ' Urlmanager ' + = [' class ' = ' Common\components\mutilpledomainurlmanager ', ' domains ' = > [' CRM ' = '/'. DOMAIN_CRM, ' admin ' = '/'. Domain_admin, ' hr ' = '/'. Domain_hr, ' oa ' = '/'. Domain_oa, ' frontend ' = '/'. Domain_frontend, ' backend ' = '/'. Domain_backend,//' img ' = '/'. Domain_img, ' api ' = '/'. DOMAIN_API, ' login ' = '/'. Domain_login,],//' baseUrl ' = ' http://'. Domain_login. '? redirecturl=http://'. Domain_home, ' showscriptname ' = False, ' enableprettyurl ' = true,//Beautify URL ' enable              Strictparsing ' = True,//set with or without ' s '; ' Suffix ' and '. php ', ' rules ' = [' ' = ' = ' site/login ',//if not here, the access domain name cannot be opened directly     Default action (remove "site/login" from URL)]      ], 

4. Supplement 3rd Step missing mutilpledomainurlmanager.php file mutilpledomainurlmanager.php, this file is stored according to the namespace I gave you.

 
  Getbaseurl ();        if ($domain) {            if (!isset ($this->domains[$domain])) {                throw new \yii\base\invalidconfigexception (' please Configure Urlmanager of Domain "'. $domain. '".');            }            $this->setbaseurl ($this->domains[$domain]);        }        $url = Parent::createurl ($params);        $this->setbaseurl ($bak);        return $url;    }}

Note: Used to get the domain URL. 5. Modify the sitecontroller.php login method under the Login module

    Login Public Function Actionlogin () {//Gets the current URL $URL =yii:: $app->request->gethostinfo (). Y        II:: $app->request->url; $URL 1= ' http://'.         DOMAIN_CRM;         $redirectURL =yii:: $app->request->get (' RedirectURL '); $redirectURL 1= ' http://'.         Domain_login;        $model = new LoginForm (); Tagdependency::invalidate (Yii:: $app->cache, [' Session: '.         Yii:: $app->session->id]); Verify that you are logged in, non-empty for login if (!\yii:: $app->user->isguest) {if (!empty ($redirectURL)) {$this-           >actionlogout ();//Mandatory exit Login return $this->redirect ($URL); }else{//redirecturl does not exist, the submission form determines if ($this->sitelogin) {if ($model-                        >load (Yii:: $app->request->post ()) && $model->login ()) {//Determine if the account is prohibited from logging in if (Empty ($t _status= $model->user->attributes[' t_status ') && $t _status==0) {return $this->error ($redirectURL 1,[yii::t (' Yii ', ' The account is prohibited from L                       Ogging in, please contact the administrator! ')];                             }else{if (empty ($redirectURL)) return $this->redirect ($URL 1,301);                        return $this->redirect ($redirectURL, 301);                            }} else {return $this->renderpartial (' Login ', [                    ' Model ' = $model,]);                }}else{return $this->gohome (); }}} or else {//redirecturl exists, submit the form to determine if ($model->load (Yii:: $app->request- >post ()) && $model->login ()) {//Determine if the account is prohibited from logging on if (empty ($t _status= $model-                    >user->attributes[' T_status ') && $t _status==0) { if (empty ($redirectURL)) {return $this->error ($redirectURL 1,[yii::t (' Yii ', ' The account is Prohib                    ited from logging on, please contact the administrator! ')]; } return $this->error ($URL, [Yii::t (' Yii ', ' The account was prohibited from logging on, please contact                 The administrator! ')];                                    }else{if (empty ($redirectURL)) return $this->redirect ($URL 1,301);                 return $this->redirect ($redirectURL, 301);  }} else {return $this->renderpartial (' login ', [' model ' =            $model,]); }        }    }

6, modify the sitecontroller.php login method under the Frontend module

Public Function Actionlogin ()    {          //Gets the previous URL        $URL =yii:: $app->request->gethostinfo (). Yii:: $app->user->getreturnurl ();          if (!\yii:: $app->user->isguest) {             return $this->redirect ('/HTTP '). Domain_login. '? Redirecturl= '. $URL);        }        $model = new LoginForm ();        if ($model->load (Yii:: $app->request->post ()) && $model->login ()) {             return $this->goback ( );        } else {             if (!empty ($URL)) {                 return $this->redirect (' http://'). Domain_login. '? Redirecturl= '. $URL);            } else{                 return $this->renderpartial (' login ', [                                ' model ' = ' $model,                            ]    }}}

7. Add the following code to the top of the frontendviewsdefaultlayoutsmain.php

$redirectURL = ' http://'. Domain_login. '? Redirecturl= '. Yii:: $app->request->gethostinfo (). Yii:: $app->request->url;

8, finally in the exit a tag so output .

Note: In other modules such as: backend, CRM and so on imitate me this frontend realization idea to change, can realize the whole project SSO login mechanism.

Alert note

1, in the 1th step, the dynamic acquisition of the domain name without WWW, this step must do domain name judgment processing, such as: www.xxx.com,www.xxx.com.cn,www.xxx.com:8099, such as these may appear domain names, to ensure that the domain name can be used to implement the mechanism of login exit.

2. In the 5th and 7th steps, use Yii2 's Own method Yii:: $app->request->gethostinfo (). Yii:: $app->request->url getting the current URL is a convenient and efficient way to reduce the redundancy of your code.

3, in the 6th step of the Frontend module under the sitecontroller.php login method, with the Yii2 method Yii:: $app->request->gethostinfo (). Yii:: $app->user->getreturnurl () Gets the previous URL, where it is important to pay special attention to getting the "last URL" instead of the current URL, and getting the current URL becomes login.xxx.com, which is not correct.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.