이 글에서는 로그인, 로그아웃, 자동 로그인 기능을 구현하기 위한 Yii2 프레임워크의 방법을 주로 소개하며, 로그인, 로그아웃, 자동 로그인 기능을 구현하기 위한 Yii2 프레임워크의 원리, 구현 방법 및 관련 동작 주의 사항을 예제 형식으로 자세히 분석합니다. . 도움이 필요한 친구들이 참고해서 모두에게 도움이 되기를 바랍니다.
이 문서의 예에서는 Yii2 프레임워크가 로그인, 로그아웃 및 자동 로그인 기능을 구현하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.
자동 로그인의 원리는 매우 간단합니다. 이는 주로 쿠키를 사용하여 이루어지며, 최초 로그인 시, 다음 로그인 시 자동 로그인을 선택하면 쿠키에 사용자의 인증정보가 저장됩니다. 더.달.
다음번 로그인 시에는 먼저 사용자 정보가 쿠키에 저장되어 있는지 확인하세요. 그렇다면 쿠키에 저장된 사용자 정보를 이용하여 로그인하세요.
사용자 구성요소 구성첫 번째 설정 구성 파일의 구성 요소에 있습니다. 사용자 구성 요소
'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ],
enableAutoLogin
이 자동 로그인 기능 활성화 여부를 결정하는 데 사용되는 것을 볼 수 있습니다. 이는 인터페이스의 다음 자동 로그인과 관련이 없습니다.
enableAutoLogin이 true인 경우에만 다음 번에 자동 로그인을 선택하면 사용자 정보가 쿠키에 저장되며 다음 번 쿠키의 유효 기간은 3600*24*30초로 설정됩니다. . 로그인 이제 Yii에서 어떻게 구현되는지 살펴보겠습니다.
1. 최초 로그인 시 쿠키 저장
1. 로그인 기능
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(); }
여기서는 간단한 로그인 후, switchIdentity
메소드를 실행하여 설정을 합니다. 인증정보.
2.switchIdentity는 인증 정보를 설정합니다.
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)); } }
이 메소드가 더 중요하며 종료 시 호출해야 합니다.
이 방법에는 크게 세 가지 기능이 있습니다
① 세션의 유효 기간을 설정합니다
② 쿠키의 유효 기간이 0보다 크고 자동 로그인이 허용되는 경우 사용자의 인증 정보를 쿠키에 저장합니다
3 자동 로그인이 허용된 경우 쿠키 정보를 삭제하세요. 나갈 때 호출됩니다. 종료 시 전달된
$identity는 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); }
쿠키에 저장된 사용자 정보에는 세 가지 값이 포함됩니다:
$identity->getId()
$duration$identity->getId()
$identity->getAuthKey()
$duration
getId()和getAuthKey()是在IdentityInterface接口中的。我们也知道在设置User组件的时候,这个User Model是必须要实现IdentityInterface接口的。所以,可以在User Model中得到前两个值,第三值就是cookie的有效期。
二、自动从cookie登录
从上面我们知道用户的认证信息已经存储到cookie中了,那么下次的时候直接从cookie里面取信息然后设置就可以了。
1、AccessControl用户访问控制
Yii提供了AccessControl来判断用户是否登录,有了这个就不需要在每一个action里面再判断了
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['logout'], 'rules' => [ [ 'actions' => ['logout'], 'allow' => true, 'roles' => ['@'], ], ], ], ]; }
2、getIsGuest、getIdentity判断是否认证用户
isGuest是自动登录过程中最重要的属性。
在上面的AccessControl访问控制里面通过IsGuest属性来判断是否是认证用户,然后在getIsGuest方法里面是调用getIdentity来获取用户信息,如果不为空就说明是认证用户,否则就是游客(未登录)。
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 重新生成用户认证信息
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(); } } }
这一部分先通过session来判断用户,因为用户登录后就已经存在于session中了。然后再判断如果是自动登录,那么就通过cookie信息来登录。
4、通过保存的Cookie信息来登录 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__); } } } }
先读取cookie值,然后$data = json_decode($value, true);
IdentityInterface 인터페이스에 있습니다. 또한 User 구성 요소를 설정할 때 User 모델이 IdentityInterface 인터페이스를 구현해야 한다는 것도 알고 있습니다. 따라서 User Model에서 처음 두 값을 얻을 수 있고 세 번째 값은 쿠키의 유효 기간입니다.
2. 쿠키에서 자동 로그인
위에서 사용자의 인증 정보가 쿠키에 저장되어 있는 것을 알 수 있으므로 다음번에는 쿠키에서 직접 정보를 받아 설정하면 됩니다.
1. AccessControl 사용자 액세스 제어Yii는 사용자의 로그인 여부를 확인하는 AccessControl을 제공합니다. 이를 통해 모든 작업을 판단할 필요가 없습니다
$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);🎜🎜2. 인증된 사용자 🎜🎜🎜isGuest는 자동 로그인 프로세스에서 가장 중요한 속성입니다. 🎜🎜위의 AccessControl 액세스 제어에서 🎜IsGuest🎜 속성을 사용하여 인증된 사용자인지 확인한 다음 🎜getIsGuest 메소드🎜에서 🎜getIdentity🎜를 호출하여 비어 있지 않으면 사용자 정보를 얻는다는 의미입니다. 이는 인증된 사용자이고, 그렇지 않으면 게스트(로그인되지 않음)입니다. 🎜🎜🎜🎜
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)); } }🎜🎜3. renewAuthStatus는 사용자 인증 정보를 다시 생성합니다🎜🎜🎜🎜🎜rrreee🎜이 부분은 로그인 후 세션에 이미 사용자가 존재하기 때문에 먼저 세션을 통해 사용자를 판단합니다. 그런 다음 자동 로그인인지 확인하고, 쿠키 정보를 통해 로그인합니다. 🎜🎜🎜4. 저장된 쿠키 정보를 통해 로그인합니다. loginByCookie🎜🎜🎜🎜🎜rrreee🎜먼저 쿠키 값을 읽은 후
$data = json_decode($value, true);
로 역직렬화합니다. 배열. 🎜🎜위 코드를 보면 자동 로그인을 위해서는 이 세 가지 값이 반드시 값을 가지고 있어야 한다는 것을 알 수 있습니다. 또한 🎜findIdentity🎜 및 🎜validateAuthKey🎜 두 가지 방법도 사용자 모델에서 구현되어야 합니다. 🎜🎜로그인 후 쿠키의 유효기간을 재설정하여 항상 유효하도록 할 수 있습니다. 🎜🎜🎜🎜rrreee🎜🎜🎜3. 로그아웃 종료🎜🎜🎜🎜🎜🎜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信息。
相关推荐:
위 내용은 Yii2 프레임워크는 로그인, 로그아웃 및 자동 로그인 기능을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Steam登录错误E84是Steam用户在多次登录尝试中遇到的常见登录。如果您无法登录Steam,则无法执行任何有用的操作。如果您不先处理此E84登录错误,您将面临大量问题。初步解决方法–1.如果您是第一次在Steam中遇到此E84错误,重新启动系统可能会修复它。关闭Steam应用程序。将其从系统托盘中退出。然后,重新启动系统并重试整个过程。2.检查互联网连接是否有故障。如果您的互联网连接速度较慢,Steam登录可能会引发E84。修复1–将noreactlogin添加到Steam可执行文件您必须

用户使用wallpaperengine可以获得各种壁纸,有很多用户不知道为什么wallpaperengine退出后壁纸没了,动态壁纸必须在你所安装壁纸的软件开启的情况下才会运行在桌面上。为什么wallpaperengine退出后壁纸没了1、动态壁纸必须在你所安装壁纸的软件开启的情况下才会运行在桌面上。2、wallpaperengine是覆盖原来的壁纸,退出当然就没了。3、关了之后壁纸还在除非文件格式是图片类型的,可以通过一些手段获取,不过这样不是动态的。4、Windows里没有用视频或动态图当壁

1.1.1.1上网认证系统登录方法:1、搜索校园网无线信号并连接;2、打开浏览器,在弹出的身份验证界面选择“自助服务”;3、输入用户名和初始密码进行登录;4、完善个人信息并设置为强密码即可。

在此前的win11更新中,我们可以跳过微软账户的登录,但是最新的win11家庭版强制用户登录微软账号才能进行安装,但是登录微软账号会带来很多麻烦,很多朋友想在安装完成后退出,下面小编就来教大家一下退出方法吧。win11怎么退出微软账号1、首先点击下方的开始菜单,在其中找到“设置”,如图所示。2、在设置界面中找到“用户”或“accounts”选项。3、在用户界面中找到“改用本地账户登录”,一行蓝色文字。4、然后只要输入我们本地账户的密码就可以登录本地账户,退出微软账号了。

在我们使用win7操作系统的过程中,我们通常会给电脑设置一个密码。最近就有小伙伴想要了解win7登陆了怎么查看电脑密码,其实win7查看电脑密码的方法非常简单。今天小编就来告诉大家win7查看电脑密码怎么操作。下面就让我们一起来看看吧!win7查看电脑密码的方法:1、按下win键+r键,输入rundll32netplwiz.dll,UsersRunDll,然后点击确定。2、取消勾选“要使用本机,用户必须输入用户名和密码”3、取消后点击确定,在弹出的对话框中不要输入你想让电脑每次自动登录的账户和密

1、登录美团账号后首先需要点击【我的】功能。2、进入到【我的】页面后,接着再点击页面中的【进入钱包】功能。3、此时会弹出【美团钱包】页面,之后下拉页面到底部后在【更多服务】栏中点击【美团互助】功能。4、这时会进入到【美团互助】页面,接着再点击该页面的【查看详情】功能。5、进入到【互助详情】页面后再次把这个页面下拉到最底部,然后点击【放弃保障】功能。6、此时会弹出一个对话框,接着点击对话框中的【坚决退出】功能,这样就成功的退出美团互助了。

随着移动互联网的迅猛发展,社交媒体成为人们生活中不可或缺的一部分。而作为其中最受欢迎的社交平台之一,抖音以其短视频内容和生动有趣的创意赢得了广大用户的喜爱。在抖音上,很多用户都会加入各种粉丝团,那么抖音粉丝团究竟有什么用呢?一、抖音粉丝团有什么用?抖音粉丝团为用户提供了一个聚集兴趣爱好者的社区。在这个社区里,用户可以找到与自己志同道合的人,共同探讨和分享感兴趣的话题。无论是追星族、音乐爱好者还是美食达人,只要你有相同的兴趣爱好,就能够在抖音粉丝团中找到属于自己的小圈子。抖音粉丝团也为用户提供了一

在许多网络应用程序中,登录是一项必须的操作。然而,在一些情况下,尤其是在一些无需提供极高安全性的应用程序中,我们可以实现免登录功能,减轻用户登录的时间和操作次数。下面我们将介绍如何通过Javascript实现免登录功能。步骤一:使用cookie存储登录状态Cookies是一种为Web提供的数据存储方式,它可以将数据存储在用户本地计算机中。通过设置cookie


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

Dreamweaver Mac版
시각적 웹 개발 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.
