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

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

  yii框架中接口access_token认证401错误_第1张图片

  产品表(product)

2.修改Member.php

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

 '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

 

    
    
        1
        zhangsan
        
        
        
        
        
        
        
        
        
        
        
    
    <_links>
        
            
                http://api.yii.com/project/product?access-token=e10adc3949ba59abbe56e057f20f883e&page=1
            
        
    
    <_meta>
        1
        1
        1
        20
    
http://api.yii.com/project/product?access-token=56444

Unauthorized
Your request was made with invalid credentials.
0
401
yii\web\UnauthorizedHttpException

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

你可能感兴趣的:(yii2框架)