Yii2 Framework RESTful API Tutorial (ii)-formatted response, authorization authentication and rate limiting

Source: Internet
Author: User
Tags findone oauth php class yii

Previously wrote a YII2 framework RESTful API Tutorial (i)-Quick start, today go ahead and explore the YII2 RESTful format response, authorization authentication and rate limiting three parts

I. Directory structure

First, list the files that need to be changed. The directory is as follows:

web├─common│      └─models  │              └user.php└─frontend        ├─config        │   └main.php        └─controllers            └bookcontroller.php
Second, 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 property. For example, to return the JSON format, modify the frontend/controllers/bookcontroller.php, and add the Red Tag 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 for the Formats property support MIME types, and values must support the response format name in Yii\web\response::formatters.

Third, authorized certification

RESTful APIs are 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 component (not necessary, but recommended):
Set the Yii\web\user::enablesession property to False (because the restful APIs are stateless, and when Yii\web\user::enablesession is false, The user authentication status in the request cannot be maintained by the session)
Set the Yii\web\user::loginurl property to Null (displays an HTTP 403 error instead of jumping to the login interface)
Specific methods, modify frontend/config/main.php, add red Tag code:

' Components ' = [    ...    ' User ' = ' + [        ' identityclass ' = ' common\models\user ',        ' enableautologin ' = ' = ',                ' enablesession ' = > False,        ' loginurl ' = null,            ],    ...]

2. 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 Tag code:

namespace Frontend\controllers;use yii\rest\activecontroller;use Yii\web\response;use yii\filters\auth\ Compositeauth;use Yii\filters\auth\queryparamauth;class Bookcontroller extends activecontroller{public $modelClass =    ' Frontend\models\book ';            Public Function Behaviors () {$behaviors = Parent::behaviors ();                $behaviors [' authenticator '] = [' class ' = = Compositeauth::classname (), ' authmethods ' = [ /* Below are three ways to verify Access_token *///1.http Basic Authentication: Access token is sent as a user name, and is applied in a scenario where access token can safely exist on the API usage, for example, A                The PI usage is a program that runs on a single server. Httpbasicauth::classname (),//2.oauth 2: The user obtains the OAUTH2 protocol-based access token from the authentication server and then sends it to a via HTTP Bearer Tokens                PI server. 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 be sent using an HTTP header acces  S token//http://localhost/user/index/index?access-token=123 queryparamauth::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 () unsigned not NULL auto_increment, ' username ' varchar () ' "Not null DEFAULT ' COMMENT ' username ', ' password_hash ' varchar (+) NOT null DEFAULT ' COMMENT ' password ', ' password_reset_token ' varchar (NOT NULL Defaul T ' COMMENT ' password token ', ' email ' varchar (+) NOT null default ' COMMENT ' mailbox ', ' auth_key ' varchar (NOT NULL default ') ' , ' status ' tinyint (3) unsigned NOT NULL default ' 0 ' COMMENT ' state ', ' created_at ' int (ten) unsigned NOT null default ' 0 ' COM ment ' creation time ', ' updated_at ' int (ten) unsigned NOT null DEFAULT ' 0 ' COMMENT ' update Time ', ' access_token ' varchar (NOT NULL DEFA ULT ' COMMENT ' restful request token ', ' allowance ' int (ten) unsigned not NULL DEFAULT ' 0 ' COMMENT ' restful remaining number of allowed requests ', ' Allowanc E_updated_at ' int (ten) unsigned not NULL DEFAULT ' 0 ' COMMENT ' RESTful request unix timestamp number ', PRIMARY key (' id '), UNIQUE KEY ' Userna Me ' (' 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 ');

Implement the Yii\web\identityinterface::findidentitybyaccesstoken () method in the Common/models/user.php class. To modify the common/models/user.php, add the red tag code:

public static function Findidentitybyaccesstoken ($token, $type = null)    The implementation of the {//findidentitybyaccesstoken () method is a 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 easily implemented in the user class as follows:    return Static::findone ([' access_token ' = $token]);    throw new NotSupportedException (' "Findidentitybyaccesstoken" is not implemented. ');}
Iv. Rate Limits

To prevent abuse, you can increase the rate limit. For example, restricting the use of each user's API is a maximum of 10 API calls within 60 seconds, and if a user receives too many requests within the same time period, the response status Code 429 (which means too many requests) is returned.

1.Yii automatically configures a behavior filter for Yii\rest\controller using Yii\filters\ratelimiter to perform rate limit checks. If the speed exceeds the limit, the rate limiter will throw a yii\web\toomanyrequestshttpexception.
Modify frontend/controllers/bookcontroller.php, add red Tag code:

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 ' = [ /* Below are three ways to verify Access_token *///1.http Basic Authentication: Access token is sent as a user name, and is applied in a scenario where access token can safely exist on the API usage, for example, A                The PI usage is a program that runs on a single server. Httpbasicauth::classname (),//2.oauth 2: The user obtains the OAUTH2 protocol-based access token from the authentication server and then sends it to a via HTTP Bearer Tokens                PI server. 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 tokens//http://localhost/user/index/inde        X?access-token=123 Queryparamauth::classname (),],];        $behaviors [' Contentnegotiator '] [' formats '] [' text/html '] = Response::format_json;    return $behaviors; }}

2. Use two columns in the user table to record the tolerance and timestamp information. To improve performance, consider using a cache or NoSQL to store this information.
Modify common/models/user.php, add red Tag 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 in a unit time, for example, [10, 60] indicates 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];    }//The UNIX timestamp when the request was saved.        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 Notsup        Portedexception (' Findidentitybyaccesstoken ' is not implemented. '); FindidentThe implementation of the Itybyaccesstoken () method is system defined//For example, a simple scenario where each user has only one access token, which can store access tokens into the Access_token column of the user table, in the user class    The simple implementation is as follows: Return Static::findone ([' access_token ' = $token]); }        ....}

A restful example of PHP: PHP implements a RESTful API instance

Yii2 Framework RESTful API Tutorial (ii)-formatted response, authorization authentication and rate limiting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.