我们讲一下RESTful api中很重要的环节—token认证。本课程主要演示如何快速借助YII2配置出简单的token认证方法,并给出扩展的思路
1.创建一个用来作权限验证的表
CREATE TABLE `clients` (
`client_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client_appid` varchar(255) NOT NULL DEFAULT '',
`client_appkey` varchar(255) NOT NULL DEFAULT '',
`client_token` varchar(255) DEFAULT NULL,
PRIMARY KEY (`client_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
然后需要创建一个Clients模型,以备后用:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Clients extends ActiveRecord
{
//指定表名称
static public function tableName()
{
return 'clients';
}
}
2.授权认证
文档:http://www.yiichina.com/doc/guide/2.0/rest-authentication
<?php
namespace app\controllers;
use yii\filters\auth\QueryParamAuth;
use yii\rest\ActiveController;
use yii\web\Response;
class UserController extends ActiveController
{
public $modelClass = 'app\models\Users';
public function init()
{
parent::init();
//关掉csrf
$this->enableCsrfValidation = false;
//关掉session
\Yii::$app->user->enableSession = false;
}
public function behaviors()
{
$behaviors = parent::behaviors();
//设置响应格式
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
//授权认证
$behaviors['authenticator'] = [
'class' => QueryParamAuth::className(), //我们使用的是QueryParamAuth
];
return $behaviors;
}
}
主要是init
和behaviors
那2句。
3.设置整个项目的验证
config/web.php
'user' => [
// 'identityClass' => 'app\models\User',
// 'enableAutoLogin' => true,
'identityClass' => 'app\models\Clients', //验证的时候调用这个类
],
4.完善Clients模型
<?php
<?php
namespace app\models;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class Clients extends ActiveRecord implements identityInterface
{
//指定表名称
static public function tableName()
{
return 'clients';
}
/**
* Finds an identity by the given ID.
* @param string|integer $id the ID to be looked for
* @return IdentityInterface the identity object that matches the given ID.
* Null should be returned if such an identity cannot be found
* or the identity is not in an active state (disabled, deleted, etc.)
*/
public static function findIdentity($id)
{
// TODO: Implement findIdentity() method.
}
/**
* Finds an identity by the given token.
* @param mixed $token the token to be looked for
* @param mixed $type the type of the token. The value of this parameter depends on the implementation.
* For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
* @return IdentityInterface the identity object that matches the given token.
* Null should be returned if such an identity cannot be found
* or the identity is not in an active state (disabled, deleted, etc.)
*/
public static function findIdentityByAccessToken($token, $type = null)
{
// TODO: Implement findIdentityByAccessToken() method.
return self::findOne(['client_token'=>$token]);
}
/**
* Returns an ID that can uniquely identify a user identity.
* @return string|integer an ID that uniquely identifies a user identity.
*/
public function getId()
{
// TODO: Implement getId() method.
}
/**
* Returns a key that can be used to check the validity of a given identity ID.
*
* The key should be unique for each individual user, and should be persistent
* so that it can be used to check the validity of the user identity.
*
* The space of such keys should be big enough to defeat potential identity attacks.
*
* This is required if [[User::enableAutoLogin]] is enabled.
* @return string a key that is used to check the validity of a given identity ID.
* @see validateAuthKey()
*/
public function getAuthKey()
{
// TODO: Implement getAuthKey() method.
}
/**
* Validates the given auth key.
*
* This is required if [[User::enableAutoLogin]] is enabled.
* @param string $authKey the given auth key
* @return boolean whether the given auth key is valid.
* @see getAuthKey()
*/
public function validateAuthKey($authKey)
{
// TODO: Implement validateAuthKey() method.
}
}
这个时候,我们再去访问:http://localhost/yiiserver/web/index.php/users 就会报错:
{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttpException"}
没有访问权限了
5.带着access_token
访问
http://localhost/yiiserver/web/index.php/users?access-token=abcabc
这样就可以正常访问了,access-token=abcabc
值abcabc
就是我们clicents表存在的client_token的值。