Home  >  Article  >  Backend Development  >  How to set permission token in php

How to set permission token in php

藏色散人
藏色散人Original
2020-08-20 10:13:002568browse

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'
);

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
        ];
    }

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!'
    ];
 }

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();复制代码

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
    );
    }

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
}

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;
}

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:
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