yii2 restfulapi QueryParamAuth验证

1.user表数据结构

 

2.修改advanced/common/models/User.php

   use yiiwebIdentityInterface;

   class User extends ActiveRecord implements IdentityInterface

  {

   //增加方法

     public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

  }

3.advancde/vender/yiisoft/yii2/web/User.php

  在最下面加四个方法

    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }
    public function getAuthKey()
    {
        return $this->auth_key;
    }
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

4.main.php在components中增加

'user' => [
            'identityClass' => 'commonmodelsUser',
            'enableAutoLogin' => true,
            'enableSession' => false,
        ],

5.usercontroller.php

  use yii estActiveController;
  use yiihelpersArrayHelper;
  use yiiwebResponse;
  use yiifiltersauthQueryParamAuth;

  //增加方法

  public function behaviors()
  {
    return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
            'class' => QueryParamAuth::className(),
        ],
    ]);
  }

6.访问方式

  http://my.qiji.com/user?access-token=123

 access-token的值只要在user表里有的,都可以

7.返回结果

  http://my.qiji.com/user/23?access-token=123的返回结果

<response>
<company_id>23</company_id>
<company_name>gregege</company_name>
<company_profile>REGRgerger</company_profile>
<transport_card/>
<business_card/>
<mechanism/>
<tax_card/>
<open_account_card/>
<head_pic/>
<ship_num>21</ship_num>
<update_time>1426326532</update_time>
<create_time>1426326532</create_time>
<status>1</status>
<remarks>ewfgvergegegergergre</remarks>
</response>
http://my.qiji.com/user/23?access-token=cuowude验证失败的返回结果
<response>
<name>Unauthorized</name>
<message>You are requesting with an invalid credential.</message>
<code>0</code>
<status>401</status>
<type>yiiwebUnauthorizedHttpException</type>
</response>
原文地址:https://www.cnblogs.com/yangbanban/p/4538733.html