thumber 2015-06-05 17:51:10 4131次浏览 1条回复 6 6 0

认证(authentication),一开始对我来说很抽象,应该很多像我一样的新手都有一样的感受。说简单些,认证就是验证你的用户名和密码是否正确,是否匹配。在实际的应用中,则体现为登录。(官方文档:Authentication is the basis of the login feature.)以下,我用自己的理解,结合文档,分析一下使用Yii2实现登录和自动登录的思路。 一、准备工作

Configure the [[yii\web\User|user]] application component;
//在配置文件中配置好user应用组件
Create a class that implements the [[yii\web\IdentityInterface]] interface.
//实现IdentityInterface接口

二、关于user

1、配置好user后,可以在全局使用Yii::$app->user访问;
2、user的重要属性,$isGuest:判断用户是否登录;$id,保存登录用户的唯一识别标识,由我们自己设置,具体如何设置,且看后文分解;
3、user的重要方法,login():将用户信息保存在session、cookie中;logout():将用户信息从session、cookie中销毁;
Note that User only maintains the user authentication status. It does NOT handle how to authenticate a user. The logic of how to authenticate a user should be done in the class implementing yii\web\IdentityInterface. 
//user组件的工作只是维护用户的认证状态(即简单的操作session和cookie)。它并不负责认证用户。认证过程的逻辑实现统统由一个实现了IdentityInterface接口的类实现;

三、关于IdentityInterface;

1这个接口定义了5个函数findIdentity();
  getId();
  findIdentityByAccessToken();
  getAuthKey();
  validateAuthKey;
这5个函数当中最重要的可能就是getId()这个函数由你实现由传递给user的对象在login的时候调用用于设置user的id属性值所以在实现这个函数的时候你返回的是什么那么user组件记住的user id就是什么其他几个函数的具体实现请参照文档

四、登录

假设我们定义了一个名为User的AR模型类(注意应用组件user的区别),User对应了一张我们保存有用户登录信息的数据表;如果我们要使用User来完成用户认证,User就必须实现上文提及的IdentityInterface;
1、服务器接受到用户提交的用户名和密码;
2、生成User实例$model;
3、赋值:$model->load(Yii::$app->request->post());
4、检查用户输入以及验证用户名和密码:$model->validate();
5、登录Yii::$app->user->login($model,$duration);

5、自动登录

1、要实现自动登录,需要设置参数$enableAutoLogin;
2、$duration必须大于零;
3、使用$isGuest判断用户是否已经登录
觉得很赞
您需要登录后才可以回复。登录 | 立即注册