Home Backend Development PHP Problem How to set token in php

How to set token in php

Sep 25, 2020 pm 02:06 PM
token

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

What to do if the login token is invalid What to do if the login token is invalid Sep 14, 2023 am 11:33 AM

Solutions to invalid login token include checking whether the Token has expired, checking whether the Token is correct, checking whether the Token has been tampered with, checking whether the Token matches the user, clearing the cache or cookies, checking the network connection and server status, logging in again or requesting a new Token. Contact technical support or developers, etc. Detailed introduction: 1. Check whether the Token has expired. The login Token usually has a validity period set. Once the validity period exceeds, it will be considered invalid, etc.

How to solve the problem of invalid login token How to solve the problem of invalid login token Sep 14, 2023 am 10:57 AM

The problem of invalid login token can be solved by checking the network connection, checking the token validity period, clearing cache and cookies, checking login status, contacting the application developer and strengthening account security. Detailed introduction: 1. Check the network connection, reconnect to the network or change the network environment; 2. Check the token validity period, obtain a new token, or contact the developer of the application; 3. Clear cache and cookies, clear browser cache and Cookie, and then log in to the application again; 4. Check the login status.

How to solve the problem of storing user tokens in Redis How to solve the problem of storing user tokens in Redis May 31, 2023 am 08:06 AM

Redis stores user tokens. When designing a system similar to e-commerce, a common requirement is that each page needs to carry logged-in user information. There are two common solutions: using cookies to save and using JWT to save. But if Redis cache is used in the system, there is also a third solution - caching the user token in Redis. Generate a token when logging in and store it in Redis //Generate a token object and save it in redis redisTemplate.opsForHash().put("token","user",user)

How Vue3+Vite uses dual tokens to achieve senseless refresh How Vue3+Vite uses dual tokens to achieve senseless refresh May 10, 2023 pm 01:10 PM

1. Token login authentication jwt: JSONWebToken. It is an authentication protocol that is generally used to verify the requested identity information and identity permissions. Composed of three parts: Header, Hayload, Signatureheader: that is, the header information, which is the basic information describing this token, json format {"alg":"HS256", //indicates the signature algorithm, the default is HMACSHA256 (written as HS256) "type":"JWT"//Indicates the type of Token. JWT tokens are uniformly written as JWT}pa

How to solve C++ syntax error: 'expected primary-expression before ':' token'? How to solve C++ syntax error: 'expected primary-expression before ':' token'? Aug 26, 2023 pm 04:06 PM

How to solve C++ syntax error: 'expectedprimary-expressionbefore':'token'? Syntax errors are a common problem in C++ programming. One of the common errors is the "expectedprimary-expressionbefore':'token" error message. This error usually occurs when using conditional expressions and the ternary operator. This article will introduce the cause of this error

What does token mean? What does token mean? Feb 29, 2024 am 10:19 AM

Token is a kind of virtual currency. It is a digital currency used to represent user permissions, record transaction information, and pay virtual currency. Token can be used to conduct transactions on a specific network, it can be used to buy or sell specific virtual currencies, and it can also be used to pay for specific services.

Andrew Ng's ChatGPT class went viral: AI gave up writing words backwards, but understood the whole world Andrew Ng's ChatGPT class went viral: AI gave up writing words backwards, but understood the whole world Jun 03, 2023 pm 09:27 PM

Unexpectedly, ChatGPT would still make stupid mistakes to this day? Master Ng Enda pointed it out at the latest class: ChatGPT will not reverse words! For example, let it reverse the word lollipop, and the output is pilollol, which is completely confusing. Oh, this is indeed a bit surprising. So much so that after a netizen who listened to the class posted a post on Reddit, it immediately attracted a large number of onlookers, and the post quickly reached 6k views. And this is not an accidental bug. Netizens found that ChatGPT is indeed unable to complete this task, and the results of our personal testing are also the same. △The actual test of ChatGPT (GPT-3.5) and even many products including Bard, Bing, Wen Xinyiyan, etc. does not work. △Actual test Bard△Actual test Wenxinyiyan

What is the usage of token in vue What is the usage of token in vue Jan 29, 2023 am 10:31 AM

Token in Vue is a string of strings generated on the server side, used as a token for client requests; its usage methods are as follows: 1. Encapsulate the method of operating local storage; 2. After encapsulating the storage, use it to Mount it into the global component; 3. Put "token" in "request.js"; 4. Set the routing guard in "index.vue" under router.

See all articles