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会自动使用yii\filters\RateLimiter为yii\rest\Controller配置一个行为过滤器来执行速率限制检查。如果速度超出限制,该速率限制器将抛出一个yii\web\TooManyRequestsHttpException。
修改frontend/controllers/BookController.php,加入红色标记代码:
namespace frontend\controllers; use yii\rest\ActiveController; use yii\web\Response; use yii\filters\auth\CompositeAuth; use yii\filters\auth\QueryParamAuth; use yii\filters\RateLimiter; class BookController extends ActiveController { public $modelClass = 'frontend\models\Book'; 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 common\models; use Yii; use yii\base\NotSupportedException; use yii\behaviors\TimestampBehavior; use yii\db\ActiveRecord; use yii\web\IdentityInterface; use yii\filters\RateLimitInterface; 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 格式化响应,授权认证和速率限制三部分详解 ,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章: