redis+token login
Preface
Login generally can be session
processed, it is relatively simple to use, but generally used more on the web
end. If you need to consider running on multiple terminals, it redis+token
is more convenient to use, why use redis
instead of using database storage token
? Of course, the database can be stored, and the background can request database query token
fields, but if you consider high concurrency, it is redis
more 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 common
class 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 token
will be token
stored in the generation radis
and set the expiration time, and then return token
to 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;
}
cache
Save is used directly here becausecache.php
the method is set in the configuration file. Forredis
details, 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 redis
query. If it token
does not exist or expires, it will be intercepted by the backend.
Tips: This is
token
not 100% safe, because if a user has obtained ittoken
, ittoken
can 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. . .