This time I will bring you a detailed explanation of the authorization verification of yii2 resetful. What are the precautions for authorization verification of yii2 resetful? The following is a practical case, let's take a look.
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 AnalysisLet’s first understand the entire logic1. The user fills in the login form on the client2. The user submits the form and the client requests
Login interfacelogin3. 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 on the client, for example In the cookie
5. The client carries the token to access the interface that needs to be verified, such as the interface for obtaining user personal information
6. The server verifies the validity of the token, and the verification passes. Anyway, the information required by the client is returned, and the verification If the verification fails, the user needs to log in again
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.
1. You should have an api application.
2. For the client, we are going to use postman for simulation. If your google browser The server has not installed postman, please download it yourself first
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 has enabled routing Beautify, and first configure the post type login operation and the get type signup-test operation
5. Close the session session of the user component
Regarding the 4th and 5th points of the above preparations, we Paste 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() ] ] ); }
如此一来,那岂不是所有访问user的操作都需要认证了?那不行,客户端第一个访问login操作的时候哪来的token,yii\filters\auth\QueryParamAuth对外提供一个属性,用于过滤不需要验证的action。我们将UserController的behaviors方法稍作修改
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'], ];
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of authorization verification of yii2 resetful. For more information, please follow other related articles on the PHP Chinese website!