


Yii2 framework implements login, logout and automatic login functions
This article mainly introduces the method of Yii2 framework to implement login, logout and automatic login functions. It analyzes in detail the principle, implementation method and related operation precautions of Yii2 framework to realize login, logout and automatic login functions in the form of examples. Friends in need You can refer to it, I hope it can help everyone.
The example in this article describes how the Yii2 framework implements login, logout and automatic login functions. Share it with everyone for your reference, the details are as follows:
The principle of automatic login is very simple. Mainly achieved by using cookies
When logging in for the first time, if the login is successful and automatic login next time is selected, the user's authentication information will be saved in the cookie, and the cookie's validity period is 1 years or months.
The next time you log in, first determine whether the user's information is stored in the cookie. If so, use the user information stored in the cookie to log in.
Configure the User component
First set the user component in the components of the configuration file
'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ],
We see that enableAutoLogin is used To determine whether to enable the automatic login function, this has nothing to do with the next automatic login on the interface.
Only when enableAutoLogin is true, if you choose to log in automatically next time, the user information will be stored in a cookie and the validity period of the cookie will be set to 3600*24 *30 seconds for next login
Now let’s take a look at how it is implemented in Yii.
1. Save cookies when logging in for the first time
1. Login login function
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 the switchIdentity method to set the authentication information.
2. SwitchIdentity sets authentication 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.
This method mainly has three functions
① Set the validity period of the session
② If the validity period of the cookie is greater than 0 and automatic login is allowed, then save the user's authentication information to
in cookie ③ If automatic login is allowed, delete the cookie information. This is called when exiting. The $identity passed in when exiting 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()<br/>$identity->getAuthKey()<br/>$duration
getId() and getAuthKey() are in IdentityInterfaceIn the interface. We also know that when setting up the User component, the User Model must implement the IdentityInterface interface. Therefore, you can get the first two values in the User Model, and the third value is the validity period of the cookie.
2. Automatically log in from cookie
From the above we know that the user’s authentication information has been stored in the cookie, so next time Just get the information directly from the cookie and set it.
1. AccessControl user access control
Yii provides AccessControl to determine whether the user is logged in. With this, there is no need to judge in each action
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['logout'], 'rules' => [ [ 'actions' => ['logout'], 'allow' => true, 'roles' => ['@'], ], ], ], ]; }
2. getIsGuest and getIdentity determine whether to authenticate the user
isGuest is the most important attribute in the automatic login process.
In the above AccessControl access control, use the IsGuest attribute to determine whether it is an authenticated user, and then call getIdentity in the getIsGuest method Get the user information. If it is not empty, it means that it is an authenticated user, otherwise it is a 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 Regenerates 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(); } } }
Pass this part first Session is used to determine the user, because the user already exists in the session after logging in. Then determine if it is an automatic login, then log in through the cookie information.
4. Log in through the saved cookie information loginByCookie
##
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__); } } } }
$data = json_decode($value, true);Deserialize into an array.
findIdentity and validateAuthKey must be implemented in the User Model.
After logging in, you can also reset the validity period of the cookie, so that it will be valid all the time.$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
3. 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)); } }
退出的时候先把当前的认证设置为null,然后再判断如果是自动登录功能则再删除相关的cookie信息。
相关推荐:
The above is the detailed content of Yii2 framework implements login, logout and automatic login functions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the "Login" button. (2) Select "Retrieve Password". (3) Enter the mobile phone number you used when registering your account

Thousands of ghosts screamed in the mountains and fields, and the sound of the exchange of weapons disappeared. The ghost generals who rushed over the mountains, with fighting spirit raging in their hearts, used the fire as their trumpet to lead hundreds of ghosts to charge into the battle. [Blazing Flame Bairen·Ibaraki Doji Collection Skin is now online] The ghost horns are blazing with flames, the gilt eyes are bursting with unruly fighting spirit, and the white jade armor pieces decorate the shirt, showing the unruly and wild momentum of the great demon. On the snow-white fluttering sleeves, red flames clung to and intertwined, and gold patterns were imprinted on them, igniting a crimson and magical color. The will-o'-the-wisps formed by the condensed demon power roared, and the fierce flames shook the mountains. Demons and ghosts who have returned from purgatory, let's punish the intruders together. [Exclusive dynamic avatar frame·Blazing Flame Bailian] [Exclusive illustration·Firework General Soul] [Biography Appreciation] [How to obtain] Ibaraki Doji’s collection skin·Blazing Flame Bailian will be available in the skin store after maintenance on December 28.

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

Users can get various wallpapers by using wallpaperengine. Many users don't know why the wallpapers are gone after wallpaperengine exits. Dynamic wallpapers can only run on the desktop when the software you installed the wallpaper is turned on. Why are the wallpapers gone after wallpaperengine exits? 1. Dynamic wallpapers can only run on the desktop when the software you installed the wallpaper is turned on. 2. WallpaperEngine overwrites the original wallpaper, and of course it will be gone when you exit. 3. The wallpaper is still there after it is turned off, unless the file format is an image type, which can be obtained through some means, but it is not dynamic. 4. There is no video or dynamic image as a wall in Windows.

How to log in to two devices with Quark? Quark Browser supports logging into two devices at the same time, but most friends don’t know how to log in to two devices with Quark Browser. Next, the editor brings users Quark to log in to two devices. Method graphic tutorials, interested users come and take a look! Quark Browser usage tutorial Quark how to log in to two devices 1. First open the Quark Browser APP and click [Quark Network Disk] on the main page; 2. Then enter the Quark Network Disk interface and select the [My Backup] service function; 3. Finally, select [Switch Device] to log in to two new devices.

In previous win11 updates, we could skip logging in with a Microsoft account, but the latest win11 home version forces users to log in with a Microsoft account to install. However, logging in with a Microsoft account will cause a lot of trouble. Many friends want to log out after the installation is completed. Let me teach you how to exit. How to log out of Microsoft account in win11 1. First click on the start menu below and find "Settings" in it, as shown in the picture. 2. Find the "Users" or "accounts" option in the settings interface. 3. Find "Log in with a local account instead" in the user interface, which is a line of blue text. 4. Then just enter the password of our local account to log in to the local account and log out of the Microsoft account.
