Home > Article > Backend Development > Authorization verification of yii2 resetful
What is a restful style API? We have written a large article before to introduce its concepts and basic operations.
Now that I have written it, what should I say today?
This article is mainly written for the deployment of APIs in actual scenarios.
Today we are going to talk about the authorization verification problems encountered by the API in those years! Exclusive work, if you benefit from reading it, please don’t forget to give me a like.
Business Analysis
Let’s first understand the entire logic
1. The user fills in the login form on the client
2. The user submits the form and the client requests the login interface login
3. The server verifies the user's account and password, and returns a valid token to the client
4. The client gets the user's token and stores it in the client such as a cookie
5 .The client carries the token to access interfaces that require verification, such as the interface for obtaining user personal information
6. The server verifies the validity of the token, and the verification passes. Anyway, it returns the information needed by the client. If the verification fails, the user needs to try again. Login
In this article, we take the user login and obtain the user's personal information as an example to give a detailed and complete explanation.
The above is the focus of this article. Don't get excited or nervous yet. After analyzing it, we will proceed step by step with the details.
Preparation work
1. You should have an api application.
2. For the client, we are going to use postman for simulation. If your Google browser has not installed postman, please do it yourself first Download
3. The user table to be tested needs to have an api_token field. If not, please add it yourself first and ensure that the field is long enough
4. The api application turns on route beautification and configures post type login first. Operation and get type signup-test operation
5. Close the session session of the user component
Regarding the 4th and 5th points of the above preparations, let’s post the code for easy understanding
'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 will add a test user later to facilitate the login operation. Other types of operations will need to be added later.
Selection of authentication class
The model class we set in api\modules\v1\controllers\UserController points to the common\models\User class. In order to illustrate the key points, we will not take it separately here. It has been rewritten. Depending on your needs, if necessary, copy a separate User class to api\models.
To verify 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 case, doesn’t all operations that access the user require authentication? That doesn't work. Where does the token come from when the client first accesses the login operation? [yii\filters\auth\QueryParamAuth] provides an external attribute for filtering actions that do not require verification. We slightly modify the behaviors method of UserController
publicfunctionbehaviors() { returnArrayHelper::merge (parent::behaviors(), [ 'authenticator'=> [ 'class'=> QueryParamAuth::className(), 'optional'=> [ 'login', 'signup-test' ], ] ] ); }
这样login操作就无需权限验证即可访问了。
添加测试用户
为了避免让客户端登录失败,我们先写一个简单的方法,往user表里面插入两条数据,便于接下来的校验。
UserController增加signupTest操作,注意此方法不属于讲解范围之内,我们仅用于方便测试。
usecommon\models\User; /** * 添加测试用户 */ publicfunctionactionSignupTest () { $user=newUser(); $user->generateAuthKey(); $user->setPassword('123456'); $user->username ='111'; $user->email ='111@111.com'; $user->save(false); return[ 'code'=> 0 ]; }
如上,我们添加了一个username是111,密码是123456的用户
登录操作
假设用户在客户端输入用户名和密码进行登录,服务端login操作其实很简单,大部分的业务逻辑处理都在api\models\loginForm上,来先看看login的实现
useapi\models\LoginForm; /** * 登录 */ 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; } }
登录成功后这里给客户端返回了用户的token,再来看看登录的具体逻辑的实现
新建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 () { parent::init(); $this->on(self::GET_API_TOKEN, [$this,'onGenerateApiToken']); } /** * @inheritdoc * 对客户端表单数据进行验证的rule */ publicfunctionrules() { return[ [['username','password'],'required'], ['password','validatePassword'], ];
相关推荐:
The above is the detailed content of Authorization verification of yii2 resetful. For more information, please follow other related articles on the PHP Chinese website!