yii框架中接口access_token认证401错误

1.用户/会员表结构(member)

  

  产品表(product)

2.修改Member.php

<?php

namespace api\modules\project\models;
use yii\web\IdentityInterface;
use yii\db\ActiveRecord;
use Yii;

/**
 * This is the model class for table "member".
 *
 * @property int $id
 * @property string $username
 * @property string $auth_key
 * @property string $passwor_hash
 * @property string $passwor_reset_token
 * @property string $email
 * @property int $status
 * @property string $access_token
 * @property int $created_at
 * @property int $updated_at
 */
class Member extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'member';
    }    //这5个方法在  yii\web\IdentityInterface 中已经定义,但是使用时必须
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }
    public function getId()
    {
        return $this->id;
    }
    public function getAuthKey()
    {
        return $this->auth_key;
    }
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'passwor_hash', 'passwor_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key', 'access_token'], 'string', 'max' => 32],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'auth_key' => 'Auth Key',
            'passwor_hash' => 'Passwor Hash',
            'passwor_reset_token' => 'Passwor Reset Token',
            'email' => 'Email',
            'status' => 'Status',
            'access_token' => 'Access Token',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }
}

4.main.php在components中增加

 /*
    *开启对yii2 restful授权认证
    */
     'user' => [
        'identityClass' => 'api\modules\project\models\Member',
        'enableAutoLogin' => true,
        'enableSession'=>false,
         //'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
     ],

5.ProductController.php

<?php
    namespace api\modules\project\controllers;
    use api\modules\project\models\product;
    use yii\rest\ActiveController;
    use yii\filters\auth\CompositeAuth;
    use yii\filters\auth\QueryParamAuth;
    class ProductController extends ActiveController
    {
        public $modelClass = 'api\modules\project\models\product';
        //增加方法
    
        //直接在响应主体内包含分页信息
        public $serializer = [
    	    'class' => 'yii\rest\Serializer',
    	    'collectionEnvelope' => 'items',
        ];
        public function behaviors()
        {
    	    $behaviors = parent::behaviors();
    	    $behaviors['authenticator'] = [
	    	'class' => CompositeAuth::className(),
	    	'authMethods' => [
		    	  QueryParamAuth::className(),
	    	],
    	    ];
    	    return $behaviors;
        }
    }

6.访问方式

  http://api.yii.com/product?access-token=e10adc3949ba59abbe56e057f20f883e

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


7.返回结果

  http://api.yii.com/project/product?access-token=e10adc3949ba59abbe56e057f20f883e
 
<response>
    <items>
    <item>
        <id>1</id>
        <name>zhangsan</name>
        <price/>
        <stock/>
        <delete_time/>
        <category_id/>
        <mai_img_url/>
        <from/>
        <create_time/>
        <update_time/>
        <summary/>
        <img_id/>
        </item>
    </items>
    <_links>
        <self>
            <href>
                http://api.yii.com/project/product?access-token=e10adc3949ba59abbe56e057f20f883e&page=1
            </href>
        </self>
    </_links>
    <_meta>
        <totalCount>1</totalCount>
        <pageCount>1</pageCount>
        <currentPage>1</currentPage>
        <perPage>20</perPage>
    </_meta>
</response>
http://api.yii.com/project/product?access-token=56444
<response>
<name>Unauthorized</name>
<message>Your request was made with invalid credentials.</message>
<code>0</code>
<status>401</status>
<type>yii\web\UnauthorizedHttpException</type>
</response>

值得注意的是,在访问接口时拼接的access-token中的 - 很多人会写成 _ ,从而导致了401错误.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值