Table of Contents
1. Process Overview
2. Specific instructions
3. Summary
Home Backend Development PHP Problem How to set permission token in php

How to set permission token in php

Aug 20, 2020 am 10:13 AM
php token

php method to set token: 1. Define the routing path to obtain the Token; 2. Establish the Service layer; 3. Use the UserToken class to handle the entire logic; 4. Establish the User class in the Model layer; 5. Verify Create corresponding verification methods and exception handling in the handler class and exception class.

How to set permission token in php

Recommended: "PHP Video Tutorial"

PHP_Set Permission Token Token

The back-end API interface we develop will have permission requirements for visitors. For example, some interfaces containing private information require the visitor to pass a Token that has been issued to the visitor in advance when requesting the interface.

This is like a token. Only when the visitor shows it will we "pass through".

The following is a record of the code writing ideas for permission tokens.


1. Process Overview

  • Define the routing path to obtain the Token and accept the code parameter (code source: WeChat server, the login system is based on the WeChat system)

  • Establish the Service layer, and create the Token base class and UserToken class in this layer

  • The UserToken class handles the entire logic: Token generation and return

  • Create the User class in the Model layer, which is responsible for reading and writing user data tables, and is used for UserToken calls in the Service layer.

  • In the validator class and exception class Create corresponding verification methods and exception handling

  • Controller->Service layer->Model layer returns value to Service layer->Service layer returns value to controller, the entire process Complete the writing of Token

2. Specific instructions

First define the routing path:

Route::post(
    'api/:version/token/user',
    'api/:version.Token/getToken'
);
Copy after login

Then create the Token controller and define the corresponding route The getToken method of the path:

public function getToken($code='') {
        (new TokenGet())->goCheck($code); // 验证器
        $token = (new UserToken($code))->get();
        return [
            'token' => $token
        ];
    }
Copy after login

Before calling the Service layer, you have to check the passed parameters, so define the TokenGet validator:

class TokenGet extends BaseValidate
{
    protected $rule = [
      'code' => 'require|isNotEmpty'
    ];

    protected $message = [
        'code' => '需要code才能获得Token!'
    ];
 }
Copy after login

Return to the Token controller, after the verification is passed , we call the UserToken class defined by the Service layer:

$token = (new UserToken($code))->get();复制代码
Copy after login

Here we discuss the Service layer and Model layer. Our general understanding is that the Service layer is an abstract encapsulation based on the Model layer.

  • The Model layer is only responsible for operating the database and returning it to the Service layer
  • Then the Service layer processes the business logic and finally returns it to the Controller layer

But I think for small projects, Service is actually on the same level as Model, because some simple interfaces can be directly connected to the Controller through the Model layer. Only relatively complex interfaces, such as user permissions, can separate different functions through the Service layer. code.

This kind of processing is more flexible. If there are a large number of really simple interfaces, there is no need to go through the Service layer once. This is more like going through the motions and has no meaning.

Go back to the code writing of the Service layer. Since there are different types of Token, we first create a Token base class, which contains some common methods. Then there is the preparation of the UserToken class that returns the token to the visitor.

Since it is based on WeChat, we need three pieces of information: code, appid, appsecret, and then assign an initial value to the UserToken class through the constructor:

function __construct($code) {
    $this->code = $code;
    $this->wxAppID = config('wx.app_id');
    $this->wxAppSecret = config('wx.app_secret');
    $this->wxLoginUrl = sprintf(
        config('wx.login_url'),
        $this->wxAppID, $this->wxAppSecret, $this->code
    );
    }
Copy after login

Then put these three in The purpose of the parameter position of the interface provided by WeChat is to obtain a complete WeChat server-side URL and request the openid we need.

Then the step of sending a network request is skipped here. The WeChat server will return an object containing openid. After judging that the value of this object is OK, we start the step of generating the token. Create the function grantToken():

private function grantToken($openidObj) {

        // 取出openid
        $openid = $openidObj['openid'];
        
        // 通过Model层调用数据库,检查openid是否已经存在
        $user = UserModel::getByOpenID($openid);
        
        // 如果存在,不处理,反之则新增一条user记录
        if ($user) {
            $uid = $user->id;
        } else {
            // 不存在,生成一条数据,具体方法略过
            $uid = $this->newUser($openid); 
        }
        
        // 生成令牌,写入缓存(具体方法见下面的定义)
        $cachedValue = $this->prepareCacheValue($openidObj, $uid);
        $token = $this->saveToCache($cachedValue);
        
        // 令牌返回到调用者端
        return $token;
}

private function prepareCacheValue($openidObj, $uid) {
    $cachedValue = $openidObj;
    $cachedValue['uid'] = $uid;
    $cachedValue['scope'] = 16; // 权限值,自己定义
    return $cachedValue;
}
    
private function saveToCache($cachedValue) {
    $key = self::generateToken(); // 生成令牌的方法
    $value = json_encode($cachedValue);
    $tokenExpire = config('setting.token_expire'); // 设定的过期时间

    $request = cache($key, $value, $tokenExpire);
        if (!$request) {
            throw new TokenException([
            'msg' => '服务器缓存异常',
            'errorCode' => 10005
        ]);
    }
    return $key; // 返回令牌:token
}
Copy after login

As you can see, the core process is:

  • Get the openid
  • Check the database and check whether the openid already exists
  • If it exists, it will not be processed, otherwise a new user record will be added
  • Generate token, prepare cache data, write to cache
  • Return token to client

generateToken()This method is defined in detail as follows:

public static function generateToken() {
    $randomChars = getRandomChars(32); // 32个字符组成一组随机字符串
    $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];  
    $salt = config('security.token_salt'); // salt 盐
    // 拼接三组字符串,进行MD5加密,然后返回
    return md5($randomChars.$timestamp.$salt);
}
    
function getRandomChars($length) {
    $str = null;
    $strPoll = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $max = strlen($strPoll) - 1;

    for ($i = 0; $i < $length; $i++) {
        $str .= $strPoll[rand(0, $max)];
    }
    return $str;
}
Copy after login

Its main function is undoubtedly to generate the token we need - Token string. It is worth mentioning that generateToken() is also used in other types of Token, so it is placed in the Token base class.

At this point, you only need to return the generated token to the Controller.

3. Summary

Token writing involves many processes. In order to avoid confusion, you must pay attention to defining the codes responsible for different tasks in different methods. As shown in the grantToken() method in the above example, this is a core method that includes all processes, but different specific processes are defined in other methods and then provided to grantToken()Method call.

After doing thisgrantToken()The method is still easy to read even though it contains all the processes.

The above is the detailed content of How to set permission token in php. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

See all articles