欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Yii2框架实现登录、退出及自动登录功能的方法详解

程序员文章站 2022-05-30 20:50:05
本文实例讲述了yii2框架实现登录、退出及自动登录功能的方法。分享给大家供大家参考,具体如下: 自动登录的原理很简单。主要就是利用cookie来实现的 在第一次登录的时...

本文实例讲述了yii2框架实现登录、退出及自动登录功能的方法。分享给大家供大家参考,具体如下:

自动登录的原理很简单。主要就是利用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中还必须要实现findidentityvalidateauthkey这两个方法。

登录完成后,还可以再重新设置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信息。

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于yii框架的php程序设计有所帮助。