In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail the sample analysis of formatting response, authorization authentication and rate limit in the Yii2 framework RESTfulAPI. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.
I. Catalog structure
First list the files that need to be changed. The catalogue is as follows:
Web ├─ common │ └─ models │ └ User.php └─ frontend ├─ config │ └ main.php └─ controllers └ BookController.php
II. Formatted response
Yii2 RESTful supports JSON and XML formats, and if you want to specify the format of the returned data, you need to configure the yii\ filters\ ContentNegotiator::formats attribute. For example, to return the JSON format, modify the frontend/controllers/BookController.php and add the red flag code:
Namespace frontend\ controllers;use yii\ rest\ ActiveController;use yii\ web\ Response;class BookController extends ActiveController {public $modelClass = 'frontend\ models\ Book';public function behaviors () {$behaviors = parent::behaviors (); $behaviors [' contentNegotiator'] ['formats'] [' text/html'] = Response::FORMAT_JSON;return $behaviors;}}
Returns the XML format: FORMAT_XML. The keys of the formats attribute supports the MIME type, while the values must support the responded format name in yii\ web\ Response::formatters.
III. Authorization and authentication
RESTful APIs is usually stateless, so each request should be accompanied by some kind of authorization credential, that is, each request sends an access token to authenticate the user.
1. Configure the user application components (not necessary, but recommended):
Set the yii\ web\ User::enableSession property to false (because RESTful APIs is stateless, when yii\ web\ User::enableSession is false, the user authentication status in the request cannot be maintained through session)
Set the yii\ web\ User::loginUrl property to null (display a HTTP 403 error instead of jumping to the login interface)
For the specific method, modify the frontend/config/main.php and add the red flag code:
'components' = > [...' user' = > ['identityClass' = >' common\ models\ User','enableAutoLogin' = > true,'enableSession' = > false,'loginUrl' = > null,],...]
two。 Configure the authenticator behavior in the controller class to specify which authentication method to use, modify the frontend/controllers/BookController.php, and add the red flag code:
Namespace frontend\ controllers;use yii\ rest\ ActiveController;use yii\ web\ Response;use yii\ filters\ auth\ CompositeAuth;use yii\ auth\ QueryParamAuth;class BookController extends ActiveController {public $modelClass = 'frontend\ models\ Book';public function behaviors () {$behaviors = parent::behaviors () $behaviors ['authenticator'] = [' class' = > CompositeAuth::className (), 'authMethods' = > [/ * the following are three ways to verify access_token basic authentication: access token is sent as a user name, and the application is used in scenarios where access token can safely have an API client. For example, the API client is a program running on a server. / / HttpBasicAuth::className (), / / 2.OAuth 2: the user obtains the access token based on the OAuth3 protocol from the authentication server and sends it to the API server through HTTP Bearer Tokens. / / HttpBearerAuth::className (), / / 3. Request parameters: access token is sent as an API URL request parameter, which should be used primarily for JSONP requests because it cannot use HTTP headers to send access token// http://localhost/user/index/index?access-token=123QueryParamAuth::className(),],];$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;return $behaviors;}}
3. Create a user table
-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' username', `password_ hash` varchar 'NOT NULL DEFAULT' 'COMMENT' password', `password_reset_ token` varchar (50) NOT NULL DEFAULT''COMMENT' password token', `email`varchar (20) NOT NULL DEFAULT''COMMENT' mailbox', `auth_ key`varchar (50) NOT NULL DEFAULT', `status` tinyint (3) unsigned NOT NULL DEFAULT'0' COMMENT 'status' `created_ at` int (10) unsigned NOT NULL DEFAULT'0' COMMENT 'creation time', `updated_ at` int (10) unsigned NOT NULL DEFAULT'0' COMMENT 'update time', `access_ token` varchar''COMMENT' restful request token', `allowance`int (10) unsigned NOT NULL DEFAULT'0' COMMENT 'restful remaining allowed requests', `allowance_updated_ at` int (10) unsigned NOT NULL DEFAULT'0' COMMENT 'restful request UNIX timestamp', 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 ('1century,' admin','$2y$13 $1KWwchqGvxDeORDt5pRW.OJarf06PjNYxe2vEGVs7e5amD3wnEX.ifold, 'z3sM2KZvXdk6mNXXrz25D3JoZlGXoJMC,' 1013, '1478686493,' 1478686493', '123',' 4' '1478686493')
Implement the yii\ web\ IdentityInterface::findIdentityByAccessToken () method in the common/models/User.php class. Modify the common/models/User.php and add the red flag code:
The implementation of the public static function findIdentityByAccessToken ($token, $type = null) {/ / findIdentityByAccessToken () method is system-defined / / for example, in a simple scenario, when each user has only one access token, the access token can be stored in the access_token column of the user table, and the method can be simply implemented in the User class, as follows: return static::findOne (['access_token' = > $token]); / / throw new NotSupportedException (' "findIdentityByAccessToken" is not implemented.');}
IV. Rate limit
To prevent abuse, the rate limit can be increased. For example, limiting the use of API per user to a maximum of 10 API calls within 60 seconds will return a response status code 429 (which means too many requests) if too many requests are received by a user in the same time period.
1.Yii automatically uses yii\ filters\ RateLimiter to configure a behavior filter for yii\ rest\ Controller to perform rate limit checks. If the speed exceeds the limit, the rate limiter throws a yii\ web\ TooManyRequestsHttpException.
Modify the frontend/controllers/BookController.php and add the red flag code:
Namespace frontend\ controllers;use yii\ rest\ ActiveController;use yii\ 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' = > [/ * the following are three ways to verify access_token basic authentication: access token is sent as a user name, and the application is used in scenarios where access token can safely have an API client. For example, the API client is a program running on a server. / / HttpBasicAuth::className (), / / 2.OAuth 2: the user obtains the access token based on the OAuth3 protocol from the authentication server and sends it to the API server through HTTP Bearer Tokens. / / HttpBearerAuth::className (), / / 3. Request parameters: access token is sent as an API URL request parameter, which should be used primarily for JSONP requests because it cannot use HTTP headers to send access token// http://localhost/user/index/index?access-token=123QueryParamAuth::className(),],];$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;return $behaviors;}}
two。 Use two columns in the user table to record tolerance and timestamp information. To improve performance, consider using caching or NoSQL to store this information.
Modify the common/models/User.php and add the red flag code:
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 {.... / / returns the maximum number of requests allowed per unit time. For example, [10,60] means a maximum of 10 requests within 60 seconds. Public function getRateLimit ($request, $action) {return [5,10];} / / returns the remaining number of allowed requests. Public function loadAllowance ($request, $action) {return [$this- > allowance, $this- > allowance_updated_at];} / / saves the UNIX timestamp of the request. Public function saveAllowance ($request, $action, $allowance, $timestamp) {$this- > allowance = $allowance;$this- > allowance_updated_at = $timest$this- > save ();}. Public static function findIdentityByAccessToken ($token, $type = null) {/ / throw new NotSupportedException ('"findIdentityByAccessToken" is not implemented.') / / the implementation of the findIdentityByAccessToken () method is system-defined / / for example, in a simple scenario, when each user has only one access token and the access token can be stored in the access_token column of the user table, the method can be simply implemented in the User class, as follows: return static::findOne (['access_token' = > $token]) }.} this is the example analysis of formatting response, authorization authentication and rate limit in Yii2 framework RESTfulAPI. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.