찾다
백엔드 개발PHP 튜토리얼Yii2 프레임워크는 로그인, 로그아웃 및 자동 로그인 기능을 구현합니다.

이 글에서는 로그인, 로그아웃, 자동 로그인 기능을 구현하기 위한 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()

$identity->getAuthKey()

$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[&#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. 로그아웃 종료🎜🎜🎜🎜🎜🎜
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框架实现可逆加密的简单方法分享

使用YII2框架开发实现微信公众号中表单提交功能教程详解

Yii2框架中日志的使用方法分析

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

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?PHP를 사용하여 이메일을 보내는 가장 좋은 방법은 무엇입니까?May 08, 2025 am 12:21 AM

TheBesteptroachForendingeMailsInphPisusingThephPmailerlibraryDuetoitsReliability, featurerichness 및 reaseofuse.phpmailersupportssmtp, proversDetailErrorHandling, supportSattachments, andenhancessecurity.foroptimalu

PHP의 종속성 주입을위한 모범 사례PHP의 종속성 주입을위한 모범 사례May 08, 2025 am 12:21 AM

의존성 주입 (DI)을 사용하는 이유는 코드의 느슨한 커플 링, 테스트 가능성 및 유지 관리 가능성을 촉진하기 때문입니다. 1) 생성자를 사용하여 종속성을 주입하고, 2) 서비스 로케이터 사용을 피하고, 3) 종속성 주입 컨테이너를 사용하여 종속성을 관리하고, 4) 주입 종속성을 통한 테스트 가능성을 향상 시키십시오.

PHP 성능 튜닝 팁 및 요령PHP 성능 튜닝 팁 및 요령May 08, 2025 am 12:20 AM

phpperformancetuningiscrucialbecauseitenhancesspeedandefficies, thearevitalforwebapplications.1) cachingsdatabaseloadandimprovesResponsetimes.2) 최적화 된 databasequerieseiesecessarycolumnsingpeedsupedsupeveval.

PHP 이메일 보안 : 이메일 보내기 모범 사례PHP 이메일 보안 : 이메일 보내기 모범 사례May 08, 2025 am 12:16 AM

theBestPracticesForendingEmailsSecurelyPinphPinclude : 1) usingecureconfigurations와 whithsmtpandstarttlSencryption, 2) 검증 및 inputSpreverventInseMeStacks, 3) 암호화에 대한 암호화와 비도시를 확인합니다

성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?성능을 위해 PHP 응용 프로그램을 어떻게 최적화합니까?May 08, 2025 am 12:08 AM

tooptimizephPapplicationsperperperperperperperperperferferferferferferferferferferperferferperferperperferferfercations.1) ubsicationScachingwithApcuTeDucedAtaFetchTimes.2) 최적화 된 ABASEABASES.3)

PHP의 종속성 주입이란 무엇입니까?PHP의 종속성 주입이란 무엇입니까?May 07, 2025 pm 03:09 PM

expendencyInphpisaDesignpatternpattern thatenhances-flexibility, testability 및 maintainabilitable externaldenciestoclasses.itallowsforloosecoupling, easiertesting throughmocking 및 modulardesign, berrequirecarefultructuringtoavoid-inje

최고의 PHP 성능 최적화 기술최고의 PHP 성능 최적화 기술May 07, 2025 pm 03:05 PM

PHP 성능 최적화는 다음 단계를 통해 달성 할 수 있습니다. 1) 스크립트 상단에 require_once 또는 include_once를 사용하여 파일로드 수를 줄입니다. 2) 데이터베이스 쿼리 수를 줄이기 위해 전처리 문 및 배치 처리를 사용하십시오. 3) Opcode 캐시에 대한 Opcache 구성; 4) PHP-FPM 최적화 프로세스 관리를 활성화하고 구성합니다. 5) CDN을 사용하여 정적 자원을 배포합니다. 6) 코드 성능 분석을 위해 Xdebug 또는 Blackfire를 사용하십시오. 7) 배열과 같은 효율적인 데이터 구조를 선택하십시오. 8) 최적화 실행을위한 모듈 식 코드를 작성하십시오.

PHP 성능 최적화 : Opcode 캐싱 사용PHP 성능 최적화 : Opcode 캐싱 사용May 07, 2025 pm 02:49 PM

opCodeCachingsIntIficInlyIntImeRimproveSphpperformanceCachingCompileDCode, retingServerLoadandResponsEtimes.1) itStoresCompyledPhpCodeInMemory, BYPASSINGPARSINGCOMPILING.2) UseOpCacheSettingParametersInphP.Ini, likeMoryConsAncme AD

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전