ThinkPHP6 project basic operations (16. actual combat part of redis+token login)

Preface

Login generally can be sessionprocessed, it is relatively simple to use, but generally used more on the webend. If you need to consider running on multiple terminals, it redis+tokenis more convenient to use, why use redisinstead of using database storage token? Of course, the database can be stored, and the background can request database query tokenfields, but if you consider high concurrency, it is redismore suitable. Generally, there are not many places to query user information, and there are more cases to determine whether a user is logged in.

1. Generate a unique token

You can create a new commonclass to specifically put methods related to strings:

<?php

namespace app\common\lib;

class Str
{
    
    
    public static function getLoginToken($string){
    
    
        // 生成 token
        $str = md5(uniqid(md5(microtime(true)), true));
        return sha1($str . $string);
    }
}

2. Set the token and return the token to the front end

In the login interface, the parameters are first judged. If the parameters are passed, they tokenwill be tokenstored in the generation radisand set the expiration time, and then return tokento the front end:

// business层的登录方法
public function login($data){
    
    
	// 省略登录参数验证与数据库更新操作
	$token = Str::getLoginToken($data["phone_number"]);
	$redisData = [
		"id" => $userId,
		"username" => $username
	];
	// 保存token到redis, 有效期7天
	$res = cache(config("radis.token_pre").$token, $redisData, 7 * 24 * 3600);
	return $res ? ["token" => $token, "username" => $username] : false;
}

cacheSave is used directly here because cache.phpthe method is set in the configuration file. For redisdetails, please refer to the 3.4 configuration cache redis in this article: Alibaba Cloud SMS combined with redis to achieve login

// controller控制器层的登录方法  调用business层的方法
$result = (new User())->login($data);
if($result){
    
    
	return show(config('status.success'), "登录成功", $result);
}else{
    
    
	return show(config('status.error'), "登录失败");
}

After the front-end request is successful, it is obtained token, and then saved. When you send the request next time, you can bring it to the backend to redisquery. If it tokendoes not exist or expires, it will be intercepted by the backend.
Insert picture description here

Tips: This is tokennot 100% safe, because if a user has obtained it token, it tokencan always access the background data during the validity period . This is also an unsolvable matter.

Three, login interceptor (login required / no login required)

To be written. . .

Guess you like

Origin blog.csdn.net/zy1281539626/article/details/111330224