Yii2 프레임워크의 자동 로그인 및 로그인 및 종료 기능 구현 방법

黄舟
풀어 주다: 2023-03-16 18:44:02
원래의
2059명이 탐색했습니다.

자동 로그인의 원리는 매우 간단합니다. 이는 주로 쿠키를 사용하여 이루어지며, 최초 로그인 시, 다음 로그인 시 자동 로그인을 선택하면 쿠키에 사용자의 인증정보가 저장됩니다. 더.달.

다음번 로그인 시에는 먼저 사용자 정보가 쿠키에 저장되어 있는지 확인하세요. 그렇다면 쿠키에 저장된 사용자 정보를 이용하여 로그인하세요.

사용자 구성요소 구성첫 번째 설정 구성 파일의 구성 요소에 있습니다. 사용자 구성 요소

'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()</p>$identity->getAuthKey() <p>$duration$identity->getId()<br/>$identity->getAuthKey()<br/>$duration

getId()和getAuthKey()是在IdentityInterface接口中的。我们也知道在设置User组件的时候,这个User Model是必须要实现IdentityInterface接口的。所以,可以在User Model中得到前两个值,第三值就是cookie的有效期。

二、自动从cookie登录

从上面我们知道用户的认证信息已经存储到cookie中了,那么下次的时候直接从cookie里面取信息然后设置就可以了。

1、AccessControl用户访问控制

Yii提供了AccessControl来判断用户是否登录,有了这个就不需要在每一个action里面再判断了


public function behaviors()
{
  return [
   &#39;access&#39; => [
    &#39;class&#39; => AccessControl::className(),
    &#39;only&#39; => [&#39;logout&#39;],
    &#39;rules&#39; => [
     [
      &#39;actions&#39; => [&#39;logout&#39;],
      &#39;allow&#39; => true,
      &#39;roles&#39; => [&#39;@&#39;],
     ],
    ],
   ],
  ];
}
로그인 후 복사

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[&#39;name&#39;];
  $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 &#39;$id&#39; logged in from $ip via cookie.", __METHOD__);
      $this->afterLogin($identity, true, $duration);
     }
    } elseif ($identity !== null) {
     Yii::warning("Invalid auth key attempted for user &#39;$id&#39;: $authKey", __METHOD__);
    }
   }
  }
}
로그인 후 복사

先读取cookie值,然后$data = json_decode($value, true);

getId() 및 getAuthKey()는

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. 로그아웃 종료🎜🎜🎜🎜🎜🎜rrreee🎜종료 시에는 우선 현재 인증을 null로 설정하신 후, 자동 로그인 기능인지 확인 후 해당 쿠키 정보를 삭제해 주세요. 🎜

위 내용은 Yii2 프레임워크의 자동 로그인 및 로그인 및 종료 기능 구현 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!