当前位置:首页 > PHP教程 > PHP常见问题

Yii2框架RESTfulAPI格式化响应,授权认证和速率限制三部分详解

之前写过一篇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 yiirestactivecontroller; 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 yiirestactivecontroller; 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为yiirestcontroller配置一个行为过滤器来执行速率限制检查。如果速度超出限制,该速率限制器将抛出一个yiiwebtoomanyrequestshttpexception。

修改frontend/controllers/bookcontroller.php,加入红色标记代码:

namespace frontendcontrollers; use yiirestactivecontroller; 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 yiibasenotsupportedexception; use yiibehaviorstimestampbehavior; 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]); } .... }

以上所述是小编给大家介绍的yii2框架restful api 格式化响应,授权认证和速率限制三部分详解 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对硕编程网站的支持!



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!