PHPのYiiフレームワークにおけるログイン機能の実装について
この記事では、Cookie による自動ログイン機能を含む、PHP の Yii フレームワークにおけるログイン関数の実装の詳細な解釈を主に紹介します。必要な友達は、
Yii のログインを参照してください。メカニズム
Yii は、アプリケーション生成時に最も基本的なユーザー ログイン メカニズムをすでに提供しています。 Yii を使用して新しいアプリケーションを生成し、protected/components ディレクトリに入ります。UserIdentity.php ファイルが表示されます。UserIdentity クラスには次のようなパブリック関数が 1 つだけあります。
public function authenticate() { $users=array( // username => password 'demo'=>'demo', 'admin'=>'admin', ); if(!isset($users[$this->username])) $this->errorCode=self::ERROR_USERNAME_INVALID; elseif($users[$this->username]!==$this->password) $this->errorCode=self::ERROR_PASSWORD_INVALID; else $this->errorCode=self::ERROR_NONE; return !$this->errorCode; }
このクラスはコンポーネント内にあり、最も基本的なユーザー検証に使用されます。この関数は、demo と admin という 2 人のユーザーを定義しているだけであることがわかります。ユーザーが非常に限られている場合、パスワードはここで直接変更して追加できます。さらにユーザーがいる場合は、後で説明します。関数の下の if else は、ユーザー名とパスワードが有効かどうかを確認するために使用され、エラーが発生した場合は ERROR_USERNAME_INVALID と ERROR_PASSWORD_INVALID が生成されます。通常、実際のユーザー名とパスワードの検証がここで実行され、ログイン後の基本的な論理処理が実行されます。
このクラスを見ただけではログイン制御のプロセスはわかりません。モデル/コントロール/ビューの原則に従って、ログイン プロセスがこれら 3 つの側面に反映されていることがわかります。まず Models フォルダーに入ると、LoginForm クラス ファイルが表示されます。このクラスは CFormModel を継承し、ログイン データとビジネス ロジックをカプセル化するフォーム モデルの派生クラスです。コア関数は次のとおりです。/** * Authenticates the password. * This is the 'authenticate' validator as declared in rules(). */ public function authenticate($attribute,$params) { $this->_identity=new UserIdentity($this->username,$this->password); if(!$this->_identity->authenticate()) $this->addError('password','用户名或密码错误'); } /** * Logs in the user using the given username and password in the model. * @return boolean whether login is successful */ public function login() { if($this->_identity===null) { $this->_identity=new UserIdentity($this->username,$this->password); $this->_identity->authenticate(); } if($this->_identity->errorCode===UserIdentity::ERROR_NONE) { $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days Yii::app()->user->login($this->_identity,$duration); return true; } else return false; }
ここでの認証では、UserIdentity クラスを使用してユーザー名とパスワードを検証し、ログイン関数はユーザー名とパスワードが認証されているかどうかを検出します。ユーザーの ID が設定されているかどうかを確認し、エラーコードが空かどうかを確認し、最後に Yii が提供するログイン機能を使用してログインします。 $duration は ID の有効期間を設定できます。
コントロールをもう一度見てみると、siteControler にログインに関するアクションがあり、その関数は次のとおりです。/** * Displays the login page */ public function actionLogin() { if (!defined('CRYPT_BLOWFISH')||!CRYPT_BLOWFISH) throw new CHttpException(500,"This application requires that PHP was compiled with Blowfish support for crypt()."); $model=new LoginForm; // if it is ajax validation request if(isset($_POST['ajax']) && $_POST['ajax']==='login-form') { echo CActiveForm::validate($model); Yii::app()->end(); } // collect user input data if(isset($_POST['LoginForm'])) { $model->attributes=$_POST['LoginForm']; // validate user input and redirect to the previous page if valid if($model->validate() && $model->login()) $this->redirect(Yii::app()->user->returnUrl); } // display the login form $this->render('login',array('model'=>$model)); }
ログインアクション LoginForm に基づいて、ログインするための POST フォームを検証するか、新しいログイン ページをレンダリングします。
最後に、ビュー ファイルはサイト フォルダー内の login.php です。これが表示されるログイン インターフェイスです。
これを整理すると、ログイン インターフェースにユーザー名とパスワードを入力すると、フォームがサイト/ログインにデータを POST し、ログオンすると LoginForm がインスタンス化される、Yii のユーザー ログイン ロジックの処理が明確にわかります。 Validate は、ルールのルールに従ってフォーム データを検証し、認証関数とログイン関数の検証を必要とします。どちらも UserIdentity の認証機能に基づいています。したがって、ログインロジックを変更する場合、LgoinFormやloginactionは変更する必要はなく、基本的にはUserIdentityの認証機能を直接変更するだけで十分です。
上記の解析は、Yii が自動生成したユーザーログインのロジック処理コードです。なかなか良い感じですね。ただし、通常、私たちのシステムは多くのユーザーによるアクセスをサポートする必要があります。コード内にユーザー名とパスワードを単にリストするのは明らかに非合理的です。もちろん、データベースに管理を依頼する方がより成熟しています。次の Mysql ステートメントに従って独自のデータベースに admin テーブルを作成するとします。
drop table if exists `admin`; create table `admin` ( `admin_id` int unsigned not null auto_increment comment '主键', `username` varchar(32) not null comment '登录名', `psw` char(40) not null comment '登录密码(两次sha1)', `nick` varchar(64) not null comment '昵称', `add_time` datetime not null comment '创建时间', `login_time` datetime null comment '最近登录时间', unique key(`username`), primary key (`admin_id`) ) engine=innodb default charset=utf8 comment='管理员表';
Mysql テーブルの作成が完了したら、gii を使用してadmin Model を作成し、元のコンポーネントの UserIdentity.php に戻り、独自のユーザー名とパスワードの検証を実装するために認証関数を書き換えます。セキュリティ上の理由から、パスワードは sha1 で 2 回暗号化されているため、収集したパスワードを sha1 で 2 回暗号化し、作成した Admin にフォームに入力したユーザー名に該当するユーザーが存在するかどうかを確認し、比較します。暗号化されたパスワード。すべてが完了したら、$this->setState('nick', $user->nick); などの setState 関数を使用して、ユーザーの共通情報を Yii のユーザーのユーザーフィールドに設定できます。文では、 Yii:app()->user->nick を使用して、データベースにクエリせずに、現在ログインしているユーザーのニックネームに直接アクセスできます。そして $user->login_time = date('Y-m-d H:i:s'); はユーザーのログイン時刻を更新し、次の文の save を通じてデータベースに保存します。
public function authenticate() { if(strlen($this->password) > 0) $this->password = sha1(sha1($this->password)); $user = Admin::model()->findByAttributes(array('username' => $this->username)); if($user == null) $this->errorCode=self::ERROR_USERNAME_INVALID; elseif( !($user instanceof Admin) || ($user->psw != $this->password) ) $this->errorCode=self::ERROR_PASSWORD_INVALID; else { $this->setState('admin_id', $user->admin_id); $this->setState('nick', $user->nick); $this->setState('username', $user->username); $user->login_time = date('Y-m-d H:i:s'); $user->save(); $this->errorCode=self::ERROR_NONE; } return !$this->errorCode; }
そして、ログイン インターフェイスを変更したい場合は、ビューのサイト フォルダーに login.php を入力し、それを次のように変更します。これにより、独自のログインプロセスが完了します。 Yii~
があると非常に便利ではないでしょうか设置自动登陆
自动登录的原理很简单。主要就是利用cookie来实现的
在第一次登录的时候,如果登录成功并且选中了下次自动登录,那么就会把用户的认证信息保存到cookie中,cookie的有效期为1年或者几个月。
在下次登录的时候先判断cookie中是否存储了用户的信息,如果有则用cookie中存储的用户信息来登录,
配置User组件
首先在配置文件的components中设置user组件
'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ],
我们看到enableAutoLogin就是用来判断是否要启用自动登录功能,这个和界面上的下次自动登录无关。
只有在enableAutoLogin为true的情况下,如果选择了下次自动登录,那么就会把用户信息存储起来放到cookie中并设置cookie的有效期为3600*24*30秒,以用于下次登录
现在我们来看看Yii中是怎样实现的。
一、第一次登录存cookie
1、login 登录功能
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)); } }
这个方法比较重要,在退出的时候也需要调用这个方法。
这个方法主要有三个功能
设置session的有效期
如果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中的用户信息包含有三个值:
$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);反序列化为数组。
这个从上面的代码可以知道要想实现自动登录,这三个值都必须有值。另外,在User Model中还必须要实现findIdentity、validateAuthKey这两个方法。
登录完成后,还可以再重新设置cookie的有效期,这样便能一起有效下去了。
$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
三、退出 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信息。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
以上がPHPのYiiフレームワークにおけるログイン機能の実装についての詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









PHP 8.4 では、いくつかの新機能、セキュリティの改善、パフォーマンスの改善が行われ、かなりの量の機能の非推奨と削除が行われています。 このガイドでは、Ubuntu、Debian、またはその派生版に PHP 8.4 をインストールする方法、または PHP 8.4 にアップグレードする方法について説明します。

Visual Studio Code (VS Code とも呼ばれる) は、すべての主要なオペレーティング システムで利用できる無料のソース コード エディター (統合開発環境 (IDE)) です。 多くのプログラミング言語の拡張機能の大規模なコレクションを備えた VS Code は、

このチュートリアルでは、PHPを使用してXMLドキュメントを効率的に処理する方法を示しています。 XML(拡張可能なマークアップ言語)は、人間の読みやすさとマシン解析の両方に合わせて設計された多用途のテキストベースのマークアップ言語です。一般的にデータストレージに使用されます

あなたが経験豊富な PHP 開発者であれば、すでにそこにいて、すでにそれを行っていると感じているかもしれません。あなたは、運用を達成するために、かなりの数のアプリケーションを開発し、数百万行のコードをデバッグし、大量のスクリプトを微調整してきました。

JWTは、JSONに基づくオープン標準であり、主にアイデンティティ認証と情報交換のために、当事者間で情報を安全に送信するために使用されます。 1。JWTは、ヘッダー、ペイロード、署名の3つの部分で構成されています。 2。JWTの実用的な原則には、JWTの生成、JWTの検証、ペイロードの解析という3つのステップが含まれます。 3. PHPでの認証にJWTを使用する場合、JWTを生成および検証でき、ユーザーの役割と許可情報を高度な使用に含めることができます。 4.一般的なエラーには、署名検証障害、トークンの有効期限、およびペイロードが大きくなります。デバッグスキルには、デバッグツールの使用とロギングが含まれます。 5.パフォーマンスの最適化とベストプラクティスには、適切な署名アルゴリズムの使用、有効期間を合理的に設定することが含まれます。

文字列は、文字、数字、シンボルを含む一連の文字です。このチュートリアルでは、さまざまな方法を使用してPHPの特定の文字列内の母音の数を計算する方法を学びます。英語の母音は、a、e、i、o、u、そしてそれらは大文字または小文字である可能性があります。 母音とは何ですか? 母音は、特定の発音を表すアルファベットのある文字です。大文字と小文字など、英語には5つの母音があります。 a、e、i、o、u 例1 入力:string = "tutorialspoint" 出力:6 説明する 文字列「TutorialSpoint」の母音は、u、o、i、a、o、iです。合計で6元があります

静的結合(静的::) PHPで後期静的結合(LSB)を実装し、クラスを定義するのではなく、静的コンテキストで呼び出しクラスを参照できるようにします。 1)解析プロセスは実行時に実行されます。2)継承関係のコールクラスを検索します。3)パフォーマンスオーバーヘッドをもたらす可能性があります。

PHPの魔法の方法は何ですか? PHPの魔法の方法には次のものが含まれます。1。\ _ \ _コンストラクト、オブジェクトの初期化に使用されます。 2。\ _ \ _リソースのクリーンアップに使用される破壊。 3。\ _ \ _呼び出し、存在しないメソッド呼び出しを処理します。 4。\ _ \ _ get、dynamic属性アクセスを実装します。 5。\ _ \ _セット、動的属性設定を実装します。これらの方法は、特定の状況で自動的に呼び出され、コードの柔軟性と効率を向上させます。
