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.
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');
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 ]; }
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 Token control 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 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 ); }
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 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 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $max = strlen($strPoll) - 1; for ($i = 0; $i < $length; $i++) { $str .= $strPoll[rand(0, $max)]; } return $str; }
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!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.