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!

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
