您的位置:首页 > 数据库 > Redis

redis----token验证

weixin_41887155 2019-08-09 12:09 435 查看
[code]<?php
/**
* token生成和验证类
* 2019.8.3
*/
namespace app\common\model;

use redis\RedisPackage;

class TokenCheck
{
public function __construct()
{
$this->redis_package = new RedisPackage();
}
/*
*用户登陆的时候,生成token,如果以后访问的接口需要登录,前端都必须带token过来
* return string(36) "123_852bf8521ec933e0a52b1f12cac6d878"
*/
public function createToken($userid){
$token = $userid.'_'.MD5( $userid.uniqid().rand( 00000000,99999999 ) );
$this->redis_package->set("admin_".$userid, serialize( array( 'time'=>time(),'token'=>$token,'user_id'=>$userid ) ) );
return $token;
}
//token登陆验证
public function checkToken( $token )
{
$maxtime=86400 * 3;  //3天过期时间,单位是秒
$user_id=strstr( $token,"_",true );  //取到用户id
$key_admin = $this->redis_package->get("admin_".$user_id);
// dump($key_admin);die;
if($key_admin){
$fcode = unserialize($key_admin);
if($fcode['token'] != $token){
returnJson(-1006,  "token异常,请重新登陆")->send();die;
}else if($fcode['time'] + $maxtime < time()){
returnJson(-1005,  "token过期,请重新登陆")->send();die;
}else{
//重新写入当前时间,确保3天以内登陆的用户一直不需要重新登陆
$this->redis_package->set("admin_".$user_id, serialize( array( 'time'=>time(),'token'=>$token,'user_id'=>$user_id ) ) );
}
}else{
returnJson(-1007,  "token不存在,请登陆")->send();die;
}
}

}

 

标签: