YII2 Resetful's Authorization verification detailed

Source: Internet
Author: User
Tags yii
This time to bring you YII2 resetful authorization to verify the details, YII2 resetful authorization to verify the considerations of what, the following is the actual case, together to see.

What is the restful style of API? We have previously written a large article to introduce its concepts and basic operations.

Now that I've written it, what do you want to say today?

This article is written primarily for deployment of APIs in real-world scenarios.

We're here today to regaling the authorization validation issues that the API has encountered over the years! Exclusive work, if you read something to benefit, remember not to forget to give me praise oh.

Business Analytics

> Let's take a look at the entire logic

1. The user fills in the login form on the client
2. User submits form, client requests Login interface login
3. The server verifies the user's account password and returns a valid token to the client
4. The client gets the token from the user, Store it in a client such as a cookie
5. The client carries token access to the interface that needs to be verified, such as access to the user's personal information interface
6. The validity of the service-side check token, check pass, anyway, return the information required by the client, verify the failure, require the user to re-login

In this paper, we use the user login, to obtain the user's personal information as an example for a detailed full version of the instructions.

Above, is the focus of this article to achieve. Don't be excited first, also don't be nervous, after analysis good, the detail part we step by step go down again.

preparation work

1. You should have an API app.
2. For the client, we are ready to use postman for simulation, if your Google browser does not already have postman installed, please download it yourself
3. The user table you want to test needs to have a api_token field, no, please add it yourself first. and ensure that the field is sufficient in length the
4.api app turns on routing and configures the login operation of the post type and the Signup-test action of the Get Type
5. Session sessions for the user component are closed

On the 4th and 5th of the above preparations, we put the code in handy to understand

' Components ' = [' user ' = ' = '   identityclass ' + ' common\models\user ',  ' enableautologin ' and ' = True ',  ' EnableSession ' and false,], ' urlmanager ' = = [  ' enableprettyurl ' = ' = ',  ' showscriptname ' = False,  ' enablestrictparsing ' = true,  ' rules ' = =   [    ' class ' = ' Yii\rest\urlrule ',    ' Controller ' = = [' V1/user '],    ' extrapatterns ' = '     = ' POST login ' = ' login ',     ' GET signup-test ' = > ' signup-test ',    ]   ],  []],//...],

Signup-test operation we add a test user behind us to facilitate the login operation. Other types of operations can be added later.

Selection of authentication classes

We set the model class in Api\modules\v1\controllers\usercontroller to point to the Common\models\user class, in order to illustrate the focus here we don't have to rewrite it alone, to see what you need, If necessary, copy the user class to api\models separately.

Verifying user Permissions We take Yii\filters\auth\queryparamauth as an example

Useyii\filters\auth\queryparamauth;publicfunctionbehaviors () {Returnarrayhelper::merge () {parent::behaviors (), [    ' authenticator ' = [     ' class ' = ' Queryparamauth::classname ()    ]  ]);

In this way, wouldn't it be that all operations that access user require authentication? That's not going to work. When the client first accesses the login operation, Token,yii\filters\auth\queryparamauth provides a property to filter the action that does not require validation. We will modify the Usercontroller behaviors method slightly.

Publicfunctionbehaviors () {Returnarrayhelper::merge () {parent::behaviors (), [    ' authenticator ' + = [     ' class ' = = Queryparamauth::classname (),    ' optional ' = [     ' login ',     ' signup-test '    ],   ]  );}

This allows the login operation to be accessed without permission validation.

Add a test user

Usercontroller Increase signuptest operation, note that this method is not within the scope of the explanation, we are only used to facilitate testing.

usecommon\models\user;/** * Add test User */publicfunctionactionsignuptest () {$user =newuser (); $user->generateauthkey () ; $user->setpassword (' 123456 '); $user->username = ' 111 '; $user->email = ' 111@111.com '; $user->save (FALSE); return[  ' code ' = 0];}

As above, we have added a username is 111, the password is 123456 of the user

Login action

Assuming that the user entered the user name and password to log in, the server login operation is actually very simple, most of the business logic processing is on the api\models\loginform, to first look at login implementation

useapi\models\loginform;/** * Login */publicfunctionactionlogin () {$model =newloginform; $model->setattributes (Yii:: $app->request->post ()); if ($user = $model->login ()) {  if ($userinstanceofIdentityInterface) {   return$user->api_token;  } else{   return$user->errors;  }} else{  return$model->errors;}}

Once the login is successful, the user token is returned to the client, and then the specific logic of the login is realized.

New api\models\loginform.php

<?phpnamespaceapi\models;useyii;useyii\base\model;usecommon\models\user;/** * Login form */ classloginformextendsmodel{public$username; public$password; private$_user; constget_api_token = ' Generate_api_ ' Token '; Publicfunctioninit () {  parent::init ();  $this->on (Self::get_api_token, [$this, ' Ongenerateapitoken ']); }/**  * @inheritdoc  * The rule *  /publicfunctionrules () {  return[   [' username ', ' which validates the client form data] Password '], ' required '],   [' Password ', ' ValidatePassword '], '     ;

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:



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.