YII2 login, logout, automatic login

Source: Internet
Author: User

The principle of automatic login is simple. The main thing is to use cookies to achieve
The first time you log in, if the login is successful and you select theNext Automatic login, the user's authentication information is saved to the cookie, and the cookie is valid for 1 years or several months.

The next time you log in to determine whether the cookie stores the user's information, if there is a cookie stored in the user information to log in,

Configuring the User component

First set up the user component in the configuration file components

' User ' = [
' Identityclass ' = ' app\models\user ',
' Enableautologin ' = true,
],

We seeEnableautologinis used to determine whether to enable the automatic login function, this and the interfaceNext Automatic loginIndependent.
Only inEnableautologinTrue, if the next automatic login is selected, the user information is stored in the cookie and the cookie is set to be valid for 3600*24*30 seconds for the next logon

Now let's look at how it's implemented in Yii.

first login and save cookies

1 login function of login


Public Function Login ($identity, $duration = 0)
{
if ($this->beforelogin ($identity, False, $duration)) {
$this->switchidentity ($identity, $duration);
$id = $identity->getid ();
$ip = Yii:: $app->getrequest ()->getuserip ();
Yii::info ("User ' $id ' logged in from $ip with duration $duration.", __method__);
$this->afterlogin ($identity, False, $duration);
}

Return! $this->getisguest ();
}

Here, simply log in and then execute theswitchidentitymethod to set the authentication information.

2, Switchidentity set up certification information

Public Function switchidentity ($identity, $duration = 0)
{
$session = Yii:: $app->getsession ();
if (! Yii_env_test) {
$session->regenerateid (TRUE);
}
$this->setidentity ($identity);
$session->remove ($this->idparam);
$session->remove ($this->authtimeoutparam);
if ($identity instanceof identityinterface) {
$session->set ($this->idparam, $identity->getid ());
if ($this->authtimeout!== null) {
$session->set ($this->authtimeoutparam, Time () + $this->authtimeout);
}
if ($duration > 0 && $this->enableautologin) {
$this->sendidentitycookie ($identity, $duration);
}
} elseif ($this->enableautologin) {
Yii:: $app->getresponse ()->getcookies ()->remove (new Cookie ($this->identitycookie));
}
}

This method is more important and needs to be called when exiting.

There are three main functions of this method

    • set session validity period
    • If the cookie is valid for more than 0 and allows automatic login, the user's authentication information is saved to the cookie
    • if automatic login is allowed, the cookie information is deleted. This is called when the exit is used. When exiting, pass in the $identity is null

protected function Sendidentitycookie ($identity, $duration)
{
$cookie = new Cookie ($this->identitycookie);
$cookie->value = Json_encode ([
$identity->getid (),
$identity->getauthkey (),
$duration,
]);
$cookie->expire = time () + $duration;
Yii:: $app->getresponse ()->getcookies ()->add ($cookie);
}

The user information stored in the cookie contains three values:

    • $identity->getid ()
    • $identity->getauthkey ()
    • $duration

GetId () and Getauthkey () are inIdentityinterfaceIn the interface. We also know that when you set up the user component, the user model must be implementedIdentityinterfaceinterface. Therefore, the first two values can be obtained in the user model, and the third value is the expiration date of the cookie.

second, automatically log in from the cookie

From the above we know that the user's authentication information has been stored in the cookie, then the next time directly from the cookie to take information and then set it up.

1. AccessControl User Access Control

Yii provides accesscontrol to determine if a user is logged in, and with this it does not need to be judged in every action.

Public Function Behaviors ()
{
return [
' Access ' = [
' Class ' = Accesscontrol::classname (),
' Only ' = [' logout '],
' Rules ' = [
[
' Actions ' = [' logout '],
' Allow ' = true,
' Roles ' = [' @ '],
],
],
],
];
}

2, Getisguest, getidentity judge whether to authenticate users

Isguest is the most important attribute in the automatic login process.
In the above AccessControl access control inside throughisguestproperty to determine whether the user is authenticated, and then theGetisguest MethodInside is calledgetidentityTo obtain the user information, if not empty the description is authenticated users, otherwise is the visitor (not logged in).

Public Function getisguest ($checkSession = True)
{
return $this->getidentity ($checkSession) = = = NULL;
}
Public Function getidentity ($checkSession = True)
{
if ($this->_identity = = = False) {
if ($checkSession) {
$this->renewauthstatus ();
} else {
return null;
}
}

return $this->_identity;
}

3, Renewauthstatus re-generate user authentication information

protected function Renewauthstatus ()
{
$session = Yii:: $app->getsession ();
$id = $session->gethassessionid () | | $session->getisactive ()? $session->get ($this->idparam): null;

if ($id = = = null) {
$identity = null;
} else {
/** @var identityinterface $class */
$class = $this->identityclass;
$identity = $class:: findidentity ($id);
}

$this->setidentity ($identity);

if ($this->authtimeout!== null && $identity!== null) {
$expire = $session->get ($this->authtimeoutparam);
if ($expire!== null && $expire < time ()) {
$this->logout (FALSE);
} else {
$session->set ($this->authtimeoutparam, Time () + $this->authtimeout);
}
}

if ($this->enableautologin) {
if ($this->getisguest ()) {
$this->loginbycookie ();
} elseif ($this->autorenewcookie) {
$this->renewidentitycookie ();
}
}
}
This part of the first through the session to determine the user, because the user login has already existed in the session. Then, if you are automatically logged in, you can log in using cookie information.

4. Log in Loginbycookie by storing cookie information

protected function Loginbycookie ()
{
$name = $this->identitycookie[' name '];
$value = Yii:: $app->getrequest ()->getcookies ()->getvalue ($name);
if ($value!== null) {
$data = Json_decode ($value, true);
if (count ($data) = = = 3 && isset ($data [0], $data [1], $data [2]) {
List ($id, $authKey, $duration) = $data;
/** @var identityinterface $class */
$class = $this->identityclass;
$identity = $class:: findidentity ($id);
if ($identity!== null && $identity->validateauthkey ($authKey)) {
if ($this->beforelogin ($identity, True, $duration)) {
$this->switchidentity ($identity, $this->autorenewcookie? $duration: 0);
$ip = Yii:: $app->getrequest ()->getuserip ();
Yii::info ("User ' $id ' logged in from $ip via cookie.", __method__);
$this->afterlogin ($identity, True, $duration);
}
} elseif ($identity!== null) {
Yii::warning ("Invalid Auth key attempted for user ' $id ': $authKey", __method__);
}
}
}
}

Read the cookie value first, and then$data = Json_decode ($value, true);deserialized into an array.

This code from the above can know that to achieve automatic login, these three values must have a value. In addition, the user model must also implement thefindidentity、ValidateauthkeyThese two methods.

Once the login is complete, you can also reset the cookie expiration date so that it works together.

$this->switchidentity ($identity, $this->autorenewcookie? $duration: 0);

third, exit logout

Public Function Logout ($destroySession = True)
{
$identity = $this->getidentity ();
if ($identity!== null && $this->beforelogout ($identity)) {
$this->switchidentity (NULL);
$id = $identity->getid ();
$ip = Yii:: $app->getrequest ()->getuserip ();
Yii::info ("User ' $id ' logged out from $ip.", __method__);
if ($destroySession) {
Yii:: $app->getsession ()->destroy ();
}
$this->afterlogout ($identity);
}

return $this->getisguest ();
}


Public Function switchidentity ($identity, $duration = 0)
{
$session = Yii:: $app->getsession ();
if (! Yii_env_test) {
$session->regenerateid (TRUE);
}
$this->setidentity ($identity);
$session->remove ($this->idparam);
$session->remove ($this->authtimeoutparam);
if ($identity instanceof identityinterface) {
$session->set ($this->idparam, $identity->getid ());
if ($this->authtimeout!== null) {
$session->set ($this->authtimeoutparam, Time () + $this->authtimeout);
}
if ($duration > 0 && $this->enableautologin) {
$this->sendidentitycookie ($identity, $duration);
}
} elseif ($this->enableautologin) {
Yii:: $app->getresponse ()->getcookies ()->remove (new Cookie ($this->identitycookie));
}
}

When exiting, set the current authentication to NULL before judging if it isAuto Sign-in functionThen delete the relevant cookie information.

YII2 login, logout, automatic login

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.