自己写的api token授权机制

    xiaoxiao2021-03-25  83

    基于laravel框架 路由自己写啊

    class TestController extends Controller { private $redis; function __construct() { $this->redis = Redis::connection(); } public function token() { // 数据库中的帐号密码验证通过 // 服务器发放token $username = request('username'); $password = request('password'); if ($username == "interface" && $password == "12345") { $token = md5(time() + mt_rand(1000, 9999)); $refresh_token = md5($token); $this->redis->set($token, $token); echo json_encode([ 'access_token' => $token, 'refresh_token' => $refresh_token, 'expire_time' => 300, 'timestamps' => time() ]); $this->redis->expireAt($token, time() + 300); $this->redis->select(1); $this->redis->set($refresh_token, $refresh_token); $this->redis->expireAt($refresh_token, time() + 36000); $this->redis->select(2); $oldToken = $this->redis->hGet($username, 'access_token');//获取旧的token $oldRefreshToken = $this->redis->hGet($username, 'refresh_token');//获取旧的refresh_token $this->redis->hSet($username, 'access_token', $token); $this->redis->hSet($username, 'refresh_token', $refresh_token); $this->redis->expireAt($username, time() + 36000); $this->redis->select(0); $this->redis->del($oldToken); $this->redis->select(1); $this->redis->del($oldRefreshToken); } else { return response()->json([ 'result_code' => 0, 'result_info' => 'No authorization!' ]); } } public function refresh_token() { $refresh_token = trim(request('refresh_token')); $username = trim(request('username')); $this->redis->select(1); if ($this->redis->exists($refresh_token)) { echo '存在'; $this->redis->select(2); $old_access_token = $this->redis->hGet($username, 'access_token'); $old_refresh_token = $this->redis->hGet($username, "refresh_token"); $this->redis->del($username); $this->redis->select(0); $this->redis->del($old_access_token); $this->redis->select(1); $this->redis->del($old_refresh_token); $this->redis->select(0); $access_token = md5(time() + mt_rand(1000, 9999)); $refresh_token = md5($access_token); $this->redis->set($access_token, $access_token); echo json_encode([ 'access_token' => $access_token, 'refresh_token' => $refresh_token ]); $this->redis->expireAt($access_token, time() + 300); $this->redis->select(1); $this->redis->set($refresh_token, $refresh_token); $this->redis->expireAt($refresh_token, time() + 36000); $this->redis->select(2); $this->redis->hSet($username, 'access_token', $access_token); $this->redis->hSet($username, 'refresh_token', $refresh_token); $this->redis->expireAt($username, time() + 36000); } else { return response()->json([ 'result_code' => 0, 'result_info' => 'No authorization!' ]); } } public function resources() { $token = request('access_token'); if ($this->redis->exists($token)) { echo "请求成功"; $this->redis->expireAt($token, time() + 300); } else { return response()->json([ 'result_code' => 0, 'result_info' => 'No authorization!' ]); } } }
    转载请注明原文地址: https://ju.6miu.com/read-21300.html

    最新回复(0)