Table of Contents
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:" >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:
PHP Token(Token)
Let’s talk about the first one first token (api_token)
Let’s talk about the second token (user_token)
Interface usage examples are as follows:
Home Backend Development PHP Tutorial Detailed explanation of token in php interface

Detailed explanation of token in php interface

Mar 20, 2018 pm 01:39 PM
php token Detailed 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、验证通过,返回数据给客户端    
?>
Copy after login

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; => []
 }
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles