Home Backend Development PHP Tutorial Detailed explanation of app interface token

Detailed explanation of app interface token

Mar 05, 2018 pm 01:05 PM
token interface Detailed explanation

1. First of all, let’s talk about what an interface is: Simply put, an interface is a bridge used by the server to return data to other programs or clients

2. The function of the interface: return according to fixed parameters Fixed data, for example, if the client passes a=1, then the server will return a's name, if the client passes a=2, the server will return a's gender, but will not return other data.

3. The role of signature: to ensure the security of interfaces and data

4. The role of token: the same as the PC login session, as the only ticket for user entry

For example: the interface between the app and the server, the interface between different programs between java and php, these interfaces generally transmit data in json format

So in order to ensure the relative security of data transmission between the mobile terminal and the server, the interface needs to be encrypted Transmission

1. Design purpose of token:
Because the APP side does not have the same session mechanism as the PC side, it cannot determine whether the user is logged in and cannot maintain the user status, so a mechanism is needed to achieve this. Session, this is the role of token. The token is the only ticket for the user to log in. As long as the token sent by the APP is consistent with the server, it can prove that you have logged in (just like when you go to a movie, you need to buy a ticket, just hold the ticket) Can enter)

2. Types of token design:
(1) Third-party login type: This token is shaped like WeChat’s access_token. The design principle is based on OAuth2.0. Its characteristics It is refreshed regularly (for example, refreshed every two hours). The purpose is because when the data source gives login permission to a third-party server, it must control its validity period and permissions. Otherwise, the third-party server can obtain users from the data source server indefinitely without the user's consent. Arbitrary data

(2) APP self-use login type: This kind of token is the token used by general APPs. Because it does not go through a third party, but the user directly obtains the data source server data, so the design is more casual, and only needs Just ensure the uniqueness of its token

3. Implementation steps for APP self-use login token:
(1) Add the token field and time_out token expiration time field to the database user table
(2) User login (also required for automatic login during registration) generate a token and the expiration time and store it in the table
(3) Before calling other interfaces, judge whether the token is correct. If it is correct, continue, if it is wrong, let the user log in again

4. APP self-use login token implementation code (company’s self-use framework and logic, mainly depends on the logic, do not copy the code directly):

(1)//下面是用户登陆时把token插入数据库的代码
$logininfo['token'] = appuser::settoken();
$time_out = strtotime("+7 days");
db::setByPk('u_adver', array('token1' => $logininfo['token'], 'time_out' => $time_out), $logininfo['id']);


(2)//下面是生成token方法代码
    public static function settoken()
    {
        $str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }

(3)//下面是每个接口都必须调用的token验证代码,验证具体实现是在(4)
$args['token'] = $_POST['token'];
$tokencheck = appuser::checktokens($args['token'], 'u_adver');
        if ($tokencheck != 90001)
        {
            $res['msg_code'] = $tokencheck;
            v_json($res);
        }


(4)//token验证方法,db::是数据库操作类,这里设置是token如果七天没被调用则需要重新登陆(也就是说用户7天没有操作APP则需要重新登陆),如果某个接口被调用,则会重新刷新过期时间
    public static function checktokens($token, $table)
    {
        $res = db::getOneForFields($table, 'time_out', 'token1 = ?', array($token));
        if (!empty($res))
        {
            if (time() - $res['time_out'] > 0) 
            {
                return 90003;  //token长时间未使用而过期,需重新登陆
            }
            $new_time_out = time() + 604800;//604800是七天
            if (db::setWhere($table, array('time_out' => $new_time_out), 'token1 = ?', array($token)))
            {
                return 90001;  //token验证成功,time_out刷新成功,可以获取接口信息
            }
        }
        return 90002;  //token错误验证失败
    }
Copy after login

Related recommendations:

PHP WeChat Methods for public accounts to verify tokens, reply content, and push messages

PHP development APP interface video tutorial

Share about writing php app interfaces and return json data example

The above is the detailed content of Detailed explanation of app interface token. 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)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard What are the internal interfaces of a computer motherboard? Recommended introduction to the internal interfaces of a computer motherboard Mar 12, 2024 pm 04:34 PM

When we assemble the computer, although the installation process is simple, we often encounter problems in the wiring. Often, users mistakenly plug the power supply line of the CPU radiator into the SYS_FAN. Although the fan can rotate, it may not work when the computer is turned on. There will be an F1 error "CPUFanError", which also causes the CPU cooler to be unable to adjust the speed intelligently. Let's share the common knowledge about the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard. Popular science on the CPU_FAN, SYS_FAN, CHA_FAN, and CPU_OPT interfaces on the computer motherboard 1. CPU_FANCPU_FAN is a dedicated interface for the CPU radiator and works at 12V

Common programming paradigms and design patterns in Go language Common programming paradigms and design patterns in Go language Mar 04, 2024 pm 06:06 PM

As a modern and efficient programming language, Go language has rich programming paradigms and design patterns that can help developers write high-quality, maintainable code. This article will introduce common programming paradigms and design patterns in the Go language and provide specific code examples. 1. Object-oriented programming In the Go language, you can use structures and methods to implement object-oriented programming. By defining a structure and binding methods to the structure, the object-oriented features of data encapsulation and behavior binding can be achieved. packagemaini

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Introduction to PHP interfaces and how to define them Introduction to PHP interfaces and how to define them Mar 23, 2024 am 09:00 AM

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

Solution to NotImplementedError() Solution to NotImplementedError() Mar 01, 2024 pm 03:10 PM

The reason for the error is in python. The reason why NotImplementedError() is thrown in Tornado may be because an abstract method or interface is not implemented. These methods or interfaces are declared in the parent class but not implemented in the child class. Subclasses need to implement these methods or interfaces to work properly. How to solve this problem is to implement the abstract method or interface declared by the parent class in the child class. If you are using a class to inherit from another class and you see this error, you should implement all the abstract methods declared in the parent class in the child class. If you are using an interface and you see this error, you should implement all methods declared in the interface in the class that implements the interface. If you are not sure which

Application of interfaces and abstract classes in design patterns in Java Application of interfaces and abstract classes in design patterns in Java May 01, 2024 pm 06:33 PM

Interfaces and abstract classes are used in design patterns for decoupling and extensibility. Interfaces define method signatures, abstract classes provide partial implementation, and subclasses must implement unimplemented methods. In the strategy pattern, the interface is used to define the algorithm, and the abstract class or concrete class provides the implementation, allowing dynamic switching of algorithms. In the observer pattern, interfaces are used to define observer behavior, and abstract or concrete classes are used to subscribe and publish notifications. In the adapter pattern, interfaces are used to adapt existing classes. Abstract classes or concrete classes can implement compatible interfaces, allowing interaction with original code.

See all articles