菜单

Authorization verification of yii2 resetful

2017年11月22日 - PHPer

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

Now that you’ve written it, would you like to say something today?

This article focuses on the deployment of API in real scenarios.

We have to look greatly in those years API encountered authentication problem today! Exclusive work, if you see some benefits, remember don’t forget to give me some praise.

Business analysis

Let’s start with the whole logic

1. users fill in the login form on the client side

2. user submits form, client requests login interface login

3. the server checks the password of the user’s account, and returns an effective token to the client

The 4. client gets the token of the user and stores it in the client, such as Cookie

5. client carries token access to verify the interface, such as access to the user’s personal information interface

6. server verify the validity of token, check through, anyway, return the client needs information, check failure, need users to log in again

In this paper, we take the user login, access to the user’s personal information as an example, a detailed full version of the note.

These are the key points in this article. Don’t get excited. Don’t be nervous. After the analysis, we’ll go on step by step in details.

Dead work

1. you should have a API Application

2. for the client, we are ready to use postman for simulation, if your Google browser has not installed postman, please download your own

3. to test the user table need to have a api_token field, no, please add your own, and ensure that the field is enough length

The 4.api application opens the routing beautification, and configures the post type login operation and the get type signup-test operation first

5. closes the session session of the user component

As for the fourth and fifth points of the preparation above, we can stick to the code to understand it conveniently

‘components’=> [

‘user’=> [

‘identityClass’=>’common\models\User’,

‘enableAutoLogin’=> true,

‘enableSession’=> false,

],

[‘urlManager’=>

‘enablePrettyUrl’=> true,

‘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 test users, to facilitate the login operation. Other types of operations need to be added later.

Selection of authentication class

We set the model class in the api\modules\v1\controllers\UserController to the common\models\User class. In order to illustrate the point, we don’t just take it out and rewrite it, see what you need, and then, if necessary, separate copy from a User class to api\models.

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 ()

]

]);

}

So, doesn’t that all access to user require authentication? That’s not true. When the client first accesses the login operation, where does token come? Yii\filters\auth\QueryParamAuth provides an attribute to filter the action that does not need to be validated. We made a slight modification to the behaviors method of UserController

(publicfunctionbehaviors)

{

ReturnArrayHelper:: merge (parent:: behaviors) ([.

‘authenticator’=> [

‘class’=&gt (QueryParamAuth:: className),

[‘optional’=>

‘login’,

‘signup-test’

],

]

]);

}

In this way, the login operation can be accessed without permission validation.

Adding test users

In order to avoid the client login failure, we first write a simple method to insert two data into the user table, which is convenient for the next check.  

UserController adds signupTest operation, note that this method is not within the scope of the explanation, we only used for convenient testing.

Usecommon\models\User;

/ * *

* add user test

.

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 added a username is 111, the password is 123456 users

Login operation

Assume that the user enters the user name and password in the client login, the server login operation is very simple, most of the business logic processing on the api\models\loginForm, to look at the implementation of login

Useapi\models\LoginForm;

  

/ * *

* login

.

PublicfunctionactionLogin ()

{

$model=newLoginForm;

(setAttributes $model-> Yii:: $app-> request-> (post));

If ($user=$model-> login) {()

(if $userinstanceofIdentityInterface) {

Return$user-> api_token;

}else{

Return$user-> errors;

}

}else{

Return$model-> errors;

}

}

After login successfully, the client’s token is returned to the client, and then the specific logic of the login is realized

New api\models\LoginForm.PHP

<? PHP

Namespaceapi\models;

  

UseYii;

Useyii\base\Model;

Usecommon\models\User;

  

/ * *

* Login form

.

ClassLoginFormextendsModel

{

Public$username;

Public$password;

  

Private$_user;

  

ConstGET_API_TOKEN =’generate_api_token’;

  

(publicfunctioninit)

{

: init (parent:);

$this-> on (self:: GET_API_TOKEN, [$this,’onGenerateApiToken’]);

}

  

  

/ * *

* @inheritdoc

* to verify client form data rule

.

(publicfunctionrules)

{

Return[

[[‘username’,’password’],’required’],

[‘password’,’validatePassword’],

];

发表评论

电子邮件地址不会被公开。