検索
ホームページバックエンド開発PHPチュートリアルYii2 フレームワークは、ログイン、ログアウト、自動ログイン機能を実装します。

この記事では、ログイン、ログアウト、自動ログイン機能を実現するための Yii2 フレームワークの原理、実装方法、および関連する操作上の注意点をサンプルの形式で詳細に分析します。 . 次に、困っている友達が参考になれば幸いです。

この記事の例では、Yii2 フレームワークがログイン、ログアウト、および自動ログイン機能を実装する方法を説明します。参考のために皆さんと共有してください。詳細は次のとおりです:

自動ログインの原理は非常に簡単です。これは主に Cookie を使用して実現されます。初回ログイン時にログインに成功し、次回から自動ログインを選択すると、ユーザーの認証情報が Cookie に保存されます。Cookie の有効期間は 1 年間です。もっと月。

次回ログインするときに、まずユーザーの情報が Cookie に保存されているかどうかを確認し、保存されている場合は、Cookie に保存されているユーザー情報を使用してログインします。

User コンポーネントを設定します設定ファイルのコンポーネント内のユーザーコンポーネント

'user' => [
 'identityClass' => 'app\models\User',
 'enableAutoLogin' => true,
],

は、自動ログイン機能を有効にするかどうかを決定するために

enableAutoLogin

が使用されていることがわかります。これは、インターフェイスでの次回の自動ログインとは関係がありません。

enableAutoLogin

がtrueの場合のみ、次回から自動的にログインすることを選択すると、ユーザー情報はCookieに保存され、次回のCookieの有効期間は3600*24*30秒に設定されますログイン それでは、Yii でどのように実装されるかを見てみましょう。

1. 初回ログイン時に Cookie を保存する

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));
  }
}

このメソッドはより重要であり、終了時に呼び出す必要があります。

この方法には主に3つの機能があります

①セッションの有効期限を設定します

②Cookieの有効期限が0より大きく、自動ログインが許可されている場合、ユーザーの認証情報をCookieに保存します

③自動ログインを許可している場合は、Cookie情報を削除してください。これは終了時に呼び出されます。終了時に渡される

$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);
}

Cookie に保存されるユーザー情報には、次の 3 つの値が含まれます:

$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 Model は IdentityInterface インターフェイスを実装する必要があることもわかっています。したがって、ユーザー モデルの最初の 2 つの値を取得でき、3 番目の値は Cookie の有効期間です。

2. Cookie から自動的にログインします


上記のことから、ユーザーの認証情報が Cookie に保存されていることがわかりますので、次回からは Cookie から直接情報を取得して設定するだけで済みます。

1. AccessControl ユーザーのアクセス制御Yii は、ユーザーがログインしているかどうかを判断する AccessControl を提供します。これにより、getIsGuest と getIdentity がログインしているかどうかを判断する必要がなくなります。認証されたユーザー


isGuest は、自動ログイン プロセスで最も重要な属性です。

🎜上記の AccessControl アクセス制御では、🎜IsGuest🎜 属性を使用して認証されたユーザーであるかどうかを判断し、🎜getIsGuest メソッド🎜で 🎜getIdentity🎜 を呼び出してユーザー情報を取得します。それが空でない場合は、それを意味します。これは認証されたユーザーであり、それ以外の場合はゲスト (ログインしていません) です。 🎜🎜🎜🎜
$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
🎜🎜3. renewAuthStatusはユーザー認証情報を再生成します🎜🎜🎜🎜🎜
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));
  }
}
🎜 この部分では、ユーザーはログイン後にセッションにすでに存在しているため、最初にセッションを通じてユーザーを判断します。次に、自動ログインかどうかを判断し、Cookie 情報を使用してログインします。 🎜🎜🎜4. 保存された Cookie 情報を使用してログインします🎜🎜🎜🎜🎜rrreee🎜最初に Cookie 値を読み取り、次にそれを $data = json_decode($value, true); に逆シリアル化します。配列 。 🎜🎜上記のコードから、自動ログインを実現するには、これら 3 つの値に値が必要であることがわかります。さらに、2 つのメソッド 🎜findIdentity🎜 と 🎜validateAuthKey🎜 もユーザー モデルに実装する必要があります。 🎜🎜ログイン後、Cookieの有効期間をリセットして、Cookieを常に有効にすることができます。 🎜🎜🎜🎜rree🎜🎜🎜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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
PHPの依存噴射とは何ですか?PHPの依存噴射とは何ですか?May 07, 2025 pm 03:09 PM

依存関係の依存性、テスト可能性、および維持可能性の依存性の依存性の依存性、および維持可能性は、エクステルンド依存性を維持する可能性があります

最高の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

opcodeCachingsificlyprovesppherformanceBycachingCompiledCode、reducingServerloadandResponsetimes.1)itStoresPhpCodeInMemory、バイパス補助補強団体

PHP依存性インジェクション:コードの維持可能性を高めますPHP依存性インジェクション:コードの維持可能性を高めますMay 07, 2025 pm 02:37 PM

依存関係注射は、PHPでの外部注入を通じてオブジェクトの依存関係を提供し、コードの保守性と柔軟性を向上させます。その実装方法には、1。コンストラクターインジェクション、2。SET値インジェクション、3。インターフェイスインジェクション。依存関係の注入を使用すると、テスト可能性と柔軟性が向上する可能性がありますが、複雑さとパフォーマンスのオーバーヘッドの増加の可能性に注意を払う必要があります。

PHPに依存関係注入を実装する方法PHPに依存関係注入を実装する方法May 07, 2025 pm 02:33 PM

PHPでの依存関係注射(DI)の実装は、手動注入またはDIコンテナを使用して実行できます。 1)手動注入は、ロガーを注入するユーザーサービスクラスなど、コンストラクターを介して依存関係を渡します。 2)DIコンテナを使用して、コンテナクラスなどの依存関係を自動的に管理し、ロガーとユーザーサービスを管理します。 DIを実装すると、コードの柔軟性とテスト能力が向上する可能性がありますが、オーバーインジェクションやサービスロケーターアンチモードなどのトラップに注意を払う必要があります。

unset()とsession_destroy()の違いは何ですか?unset()とsession_destroy()の違いは何ですか?May 04, 2025 am 12:19 AM

thedifferencebetferencefued fieneunset()andsession_destroy()isthatunset()clearsspecificsessionvariablesはsessionactiveであり、ssession_destroy()ターミナテンテンセッション

負荷分散のコンテキストでの粘着性セッション(セッションアフィニティ)とは何ですか?負荷分散のコンテキストでの粘着性セッション(セッションアフィニティ)とは何ですか?May 04, 2025 am 12:16 AM

StickysionsionsureuserRequestsoredtotheSameserverforsessiondataconsistency.1)Sessionidedificationisionidificationsisignivisionsignsignsuserstoserversusing okiesorurlmodifications.2)CondingRoutingDirectSSubSubSubsEntRequestStotheSameserver.3)LoadBalancingDistributeNewuser

PHPで利用可能なさまざまなセッション保存ハンドラーは何ですか?PHPで利用可能なさまざまなセッション保存ハンドラーは何ですか?May 04, 2025 am 12:14 AM

phpoffersvarioussionsionsavehandlers:1)ファイル:デフォルト、simplebutmaybottleneckonhigh-trafficsites.2)memcached:high-performance、yealforspeed-criticalapplications.3)redis:similartomcached、witordededpersistence.4)データベースの提供

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 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール