zoukankan      html  css  js  c++  java
  • Yii2框架RESTful API教程(二)

    之前写过一篇Yii2框架RESTful API教程(一) - 快速入门,今天接着来探究一下Yii2 RESTful的格式化响应,授权认证和速率限制三个部分

    一、目录结构

    先列出需要改动的文件。目录如下:

     
    web
     ├─ common
     │      └─ models 
     │              └ User.php
     └─ frontend
            ├─ config
            │   └ main.php
            └─ controllers
                └ BookController.php
     

    二、格式化响应

    Yii2 RESTful支持JSON和XML格式,如果想指定返回数据的格式,需要配置yiifiltersContentNegotiator::formats属性。例如,要返回JSON格式,修改frontend/controllers/BookController.php,加入红色标记代码:

     
    namespace frontendcontrollers;
    
    use yii
    estActiveController;
    use yiiwebResponse;
    
    class BookController extends ActiveController
    {
        public $modelClass = 'frontendmodelsBook';
    
        public function behaviors() {
            $behaviors = parent::behaviors();
            $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
            return $behaviors;
        }
    }
     

    返回XML格式:FORMAT_XML。formats属性的keys支持MIME类型,而values必须在yiiwebResponse::formatters中支持被响应格式名称。

    三、授权认证

    RESTful APIs通常是无状态的,因此每个请求应附带某种授权凭证,即每个请求都发送一个access token来认证用户。

    1.配置user应用组件(不是必要的,但是推荐配置):
      设置yiiwebUser::enableSession属性为false(因为RESTful APIs为无状态的,当yiiwebUser::enableSession为false,请求中的用户认证状态就不能通过session来保持)
      设置yiiwebUser::loginUrl属性为null(显示一个HTTP 403 错误而不是跳转到登录界面)
    具体方法,修改frontend/config/main.php,加入红色标记代码:

     
    'components' => [
        ...
        'user' => [
            'identityClass' => 'commonmodelsUser',
            'enableAutoLogin' => true,
            
            'enableSession' => false,
            'loginUrl' => null,
            
        ],
        ...
    ]
     

    2.在控制器类中配置authenticator行为来指定使用哪种认证方式,修改frontend/controllers/BookController.php,加入红色标记代码:

     
    namespace frontendcontrollers;
    
    use yii
    estActiveController;
    use yiiwebResponse;
    
    use yiifiltersauthCompositeAuth;
    use yiifiltersauthQueryParamAuth;
    
    class BookController extends ActiveController
    {
        public $modelClass = 'frontendmodelsBook';
    
        public function behaviors() {
            $behaviors = parent::behaviors();
        
            $behaviors['authenticator'] = [
                'class' => CompositeAuth::className(),
                'authMethods' => [
                    /*下面是三种验证access_token方式*/
                    //1.HTTP 基本认证: access token 当作用户名发送,应用在access token可安全存在API使用端的场景,例如,API使用端是运行在一台服务器上的程序。
                    //HttpBasicAuth::className(),
                    //2.OAuth 2: 使用者从认证服务器上获取基于OAuth2协议的access token,然后通过 HTTP Bearer Tokens 发送到API 服务器。
                    //HttpBearerAuth::className(),
                    //3.请求参数: access token 当作API URL请求参数发送,这种方式应主要用于JSONP请求,因为它不能使用HTTP头来发送access token
                    //http://localhost/user/index/index?access-token=123
                    QueryParamAuth::className(),
                ],
            ];
            
            $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
            return $behaviors;
        }
    }
     

    3.创建一张user表

     
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `username` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名',
      `password_hash` varchar(100) NOT NULL DEFAULT '' COMMENT '密码',
      `password_reset_token` varchar(50) NOT NULL DEFAULT '' COMMENT '密码token',
      `email` varchar(20) NOT NULL DEFAULT '' COMMENT '邮箱',
      `auth_key` varchar(50) NOT NULL DEFAULT '',
      `status` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '状态',
      `created_at` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
      `updated_at` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
      `access_token` varchar(50) NOT NULL DEFAULT '' COMMENT 'restful请求token',
      `allowance` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'restful剩余的允许的请求数',
      `allowance_updated_at` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'restful请求的UNIX时间戳数',
      PRIMARY KEY (`id`),
      UNIQUE KEY `username` (`username`),
      UNIQUE KEY `access_token` (`access_token`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES ('1', 'admin', '$2y$13$1KWwchqGvxDeORDt5pRW.OJarf06PjNYxe2vEGVs7e5amD3wnEX.i', '', '', 'z3sM2KZvXdk6mNXXrz25D3JoZlGXoJMC', '10', '1478686493', '1478686493', '123', '4', '1478686493');
     

    在common/models/User.php类中实现 yiiwebIdentityInterface::findIdentityByAccessToken()方法。修改common/models/User.php,加入红色标记代码::

     
    public static function findIdentityByAccessToken($token, $type = null)
    {
        //findIdentityByAccessToken()方法的实现是系统定义的
        //例如,一个简单的场景,当每个用户只有一个access token, 可存储access token 到user表的access_token列中, 方法可在User类中简单实现,如下所示:
        return static::findOne(['access_token' => $token]);
        //throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }
     

    四、速率限制

    为防止滥用,可以增加速率限制。例如,限制每个用户的API的使用是在60秒内最多10次的API调用,如果一个用户同一个时间段内太多的请求被接收,将返回响应状态代码 429 (这意味着过多的请求)。

    1.Yii会自动使用yiifiltersRateLimiter为yii estController配置一个行为过滤器来执行速率限制检查。如果速度超出限制,该速率限制器将抛出一个yiiwebTooManyRequestsHttpException。
    修改frontend/controllers/BookController.php,加入红色标记代码:

     
    namespace frontendcontrollers;
    
    use yii
    estActiveController;
    use yiiwebResponse;
    use yiifiltersauthCompositeAuth;
    use yiifiltersauthQueryParamAuth;
    
    use yiifiltersRateLimiter;
    
    class BookController extends ActiveController
    {
        public $modelClass = 'frontendmodelsBook';
    
        public function behaviors() {
            $behaviors = parent::behaviors();
            
            $behaviors['rateLimiter'] = [
                'class' => RateLimiter::className(),
                'enableRateLimitHeaders' => true,
            ];
            
            $behaviors['authenticator'] = [
                'class' => CompositeAuth::className(),
                'authMethods' => [
                    /*下面是三种验证access_token方式*/
                    //1.HTTP 基本认证: access token 当作用户名发送,应用在access token可安全存在API使用端的场景,例如,API使用端是运行在一台服务器上的程序。
                    //HttpBasicAuth::className(),
                    //2.OAuth 2: 使用者从认证服务器上获取基于OAuth2协议的access token,然后通过 HTTP Bearer Tokens 发送到API 服务器。
                    //HttpBearerAuth::className(),
                    //3.请求参数: access token 当作API URL请求参数发送,这种方式应主要用于JSONP请求,因为它不能使用HTTP头来发送access token
                    //http://localhost/user/index/index?access-token=123
                    QueryParamAuth::className(),
                ],
            ];
            $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
            return $behaviors;
        }
    }
     

    2.在user表中使用两列来记录容差和时间戳信息。为了提高性能,可以考虑使用缓存或NoSQL存储这些信息。
    修改common/models/User.php,加入红色标记代码:

     
    namespace commonmodels;
    
    use Yii;
    use yiiaseNotSupportedException;
    use yiiehaviorsTimestampBehavior;
    use yiidbActiveRecord;
    use yiiwebIdentityInterface;
    
    use yiifiltersRateLimitInterface;
    
    class User extends ActiveRecord implements IdentityInterface, RateLimitInterface
    {
    
        ....
    
        // 返回在单位时间内允许的请求的最大数目,例如,[10, 60] 表示在60秒内最多请求10次。
        public function getRateLimit($request, $action)
        {
            return [5, 10];
        }
    
        // 返回剩余的允许的请求数。
        public function loadAllowance($request, $action)
        {
            return [$this->allowance, $this->allowance_updated_at];
        }
    
        // 保存请求时的UNIX时间戳。
        public function saveAllowance($request, $action, $allowance, $timestamp)
        {
            $this->allowance = $allowance;
            $this->allowance_updated_at = $timestamp;
            $this->save();
        }
        
        ....
        
        public static function findIdentityByAccessToken($token, $type = null)
        {
            //throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
            //findIdentityByAccessToken()方法的实现是系统定义的
            //例如,一个简单的场景,当每个用户只有一个access token, 可存储access token 到user表的access_token列中, 方法可在User类中简单实现,如下所示:
            return static::findOne(['access_token' => $token]);
        }
        
        ....
    }
     

     PHP的RESTful实例: PHP实现RESTful风格的API实例

  • 相关阅读:
    LOJ 2550 「JSOI2018」机器人——找规律+DP
    LOJ 2548 「JSOI2018」绝地反击 ——二分图匹配+网络流手动退流
    2019.4.24 一题(CF 809E)——推式子+虚树
    LOJ 2551 「JSOI2018」列队——主席树+二分
    bzoj 2632 [ neerc 2011 ] Gcd guessing game —— 贪心
    bzoj 1927 星际竞速 —— 最小费用最大流
    bzoj 2535 & bzoj 2109 航空管制 —— 贪心+拓扑序
    bzoj 3671 随机数生成器 —— 暴力
    bzoj 2395 Timeismoney —— 最小乘积生成树
    bzoj 3157 & bzoj 3516 国王奇遇记 —— 推式子
  • 原文地址:https://www.cnblogs.com/quanzhiguo/p/7157728.html
Copyright © 2011-2022 走看看