Home > Backend Development > PHP Problem > How to set token in php

How to set token in php

PHPz
Release: 2023-03-05 21:58:01
Original
4420 people have browsed it

php method to set token: first define the routing path to obtain the token; then establish the Service layer; then create the User class in the Model layer, and create corresponding verification methods and exception handling in the validator class and exception class ;Finally complete the writing of the Token token.

How to set token in php

Recommended: "PHP Video Tutorial"

The back-end API interface we developed will have a Permission requirements, such as 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, 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, responsible for reading and writing user data tables for Service Layer's UserToken call

Create corresponding verification methods and exception handling in the validator class and exception class

Controller->Service layer->Model layer returns the value to the Service layer-> ;The Service layer returns the value to the controller, and the entire process completes 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 control Device, define the getToken method corresponding to the routing 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 Token control 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 codes for different functions through the Service layer.

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 openid

Check the database and check whether openid already exists

If it exists, do not process it, otherwise add a new user record

Generate token , prepare the cache data, write to the cache

Return the token to the client

The generateToken() 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 = &#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&#39;;    $max = strlen($strPoll) - 1;    for ($i = 0; $i < $length; $i++) {        $str .= $strPoll[rand(0, $max)];
    }    return $str;
}
Copy after login

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

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

3. Summary

The writing of tokens 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 the grantToken() method call.

After doing this, the grantToken() method is still easy to read even though it includes all processes.

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template