search
HomeBackend DevelopmentPHP TutorialDetailed explanation of token in php interface

Detailed explanation of token in php interface

Mar 20, 2018 pm 01:39 PM
phptokenDetailed explanation


This article mainly shares with you the detailed explanation of the token of the PHP interface, hoping to help everyone. Let’s first take a look at the summary of interface characteristics:

Summary of interface characteristics:

1. Because it is non-open, all interfaces are closed and only available to internal users of the company. The product is valid;

2. Because it is non-open, the OAuth protocol is not feasible because there is no intermediate user authorization process;

3. Some interfaces require users to log in to access. ;

4. Some interfaces can be accessed without user login;

PHP Token(Token)

In view of the above characteristics, the mobile terminal and Server-side communication requires 2 keys, namely 2 tokens.

The first token is for the interface (api_token);
The second token is for the user (user_token);

Let’s talk about the first one first token (api_token)

Its responsibility is to maintain the concealment and effectiveness of interface access and ensure that the interface can only be used by its own family. How to do this? The reference idea is as follows:
Generate a random string based on the common attributes shared by both the server and the client. The client generates this string, and the server also generates a string based on the same algorithm to verify the client's string.

The current interface is basically MVC mode, and the URL is basically restful style. The general format of the URL is as follows:
http://blog.snsgou.com/module name/controller name/method name?parameter name 1=Parameter value 1&Parameter name 2=Parameter value 2&Parameter name 3=Parameter value 3
The interface token generation rules are as follows:
api_token = md5 ('Module name' + 'Controller name' + 'Method name ' + '2013-12-18' + 'Encryption Key') = 770fed4ca2aabd20ae9a5dd774711de2
where
1, '2013-12-18' is the time of the day,
2, 'Encryption Key' is Private encryption key. After the mobile phone needs to register an "interface user" account on the server, the system will assign an account and password. The data table design reference is as follows:
Field name field type comment
client_id varchar( 20) Client ID
client_secret varchar(20) Client (encryption) key

Server interface verification, PHP implementation process is as follows:

<?php   
// 1、获取 GET参数 值   
$module = $_GET[&#39;mod&#39;]; $controller = $_GET[&#39;ctl&#39;]   
$action = $_GET[&#39;act&#39;]; $client_id = $_GET[&#39;client_id&#39;];   
$api_token = $_GET[&#39;api_token‘];   
// 2、根据客户端传过来的 client_id ,查询数据库,获取对应的 client_secret   
$client_secret = getClientSecretById($client_id);   
// 3、服务端重新生成一份 api_token   
$api_token_server = md5($module . $controller . $action .  date(&#39;Y-m-d&#39;, time()) .  $client_secret);   
// 4、客户端传过来的 api_token 与服务端生成的 api_token 进行校对,如果不相等,则表示验证失败   
if ($api_token != $api_token_server) {   
    exit(&#39;access deny&#39;);  // 拒绝访问 } // 5、验证通过,返回数据给客户端    
?>

Let’s talk about the second token (user_token)

Its responsibility is to protect the user’s username and password from being submitted multiple times to prevent password leakage.

If the interface requires user login, the access process is as follows:
1. The user submits the "user name" and "password" to log in (if conditions permit, it is best to use https for this step);
2. After successful login, the server returns a user_token. The generation rules are as follows:
user_token = md5('user's uid' + 'Unix timestamp') = etye0fgkgk4ca2aabd20ae9a5dd77471fgf
The server uses a data table to maintain the status of user_token , the table design is as follows:
Field name field type annotation
user_id int user ID
user_token varchar(36) user token
expire_time int expiration time (Unix timestamp)

(Note: Only the core fields are listed, please expand the others!!!)

After the server generates the user_token, it returns it to the client (storage by itself), and the client makes every interface request If the interface requires user login to access, user_id and user_token need to be passed back to the server. After the server receives these two parameters, it needs to do the following steps:

1. Detect the validity of api_token property;

2. Delete expired user_token table records;

3. Get table records based on user_id, user_token. If the table record does not exist, an error will be returned directly. If the record exists, proceed to the next step. One step;

4. Update the expiration time of user_token (extended to ensure that continuous operations will not be dropped during its validity period);

5. Return interface data;

Interface usage examples are as follows:

Request method: POST
POST parameters: title=I am the title&content=I am the content
Return data:

{       &#39;code&#39; => 1, 
// 1:成功 0:失败      
&#39;msg&#39; => &#39;操作成功&#39; 
// 登录失败、无权访问     
 &#39;data&#39; => []
 }

How to prevent token hijacking?

There is definitely a problem of token leakage. For example, if I get your mobile phone and copy your token, I can log in as you elsewhere before it expires.
A simple way to solve this problem
1. When storing, symmetrically encrypt the token and store it, and then decrypt it when used.
2. Combine the request URL, timestamp, and token and add a salt signature, and the server verifies the validity.
The starting point of both methods is: it is easier to steal your stored data, but it is more difficult to disassemble your program and hack your encryption, decryption and signature algorithms. However, it is actually not difficult to say that it is difficult, so after all, it is an approach to guard against gentlemen rather than villains.

Related recommendations:

Instance method of PHP implementing Token

Detailed explanation of token in app interface

How to set the WeChat applet url and token

The above is the detailed content of Detailed explanation of token in php interface. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)