laravel-admin 单一登录的简单实现

Laravel框架
590
0
0
2022-04-16
标签   Laravel-Admin

一、修改vendor/encore/laravel-admin/src/Controllers/AuthController.php中postLogin方法

if ($this->guard()->attempt($credentials, $remember)) {
    $res = $this->sendLoginResponse($request);//登录成功 记录token   
    $this->sendCookieToken($this->guard()->user(), $request);
    return $res;
}

二、添加方法sendCookieToken

/*
* 制作token,用于单用户登录验证
*/ 
public function sendCookieToken($member, Request $request) {
    $time = time();
    $sinleToken = md5($request->getClientIp().$member->id.$time);
    Cache::put($member->id, $time, 300);
    \Cache::put('check_code'.$member->id, null, 300);
    $request->session()->put('SINGLETOKEN', $sinleToken);
}

三、使用中间件验证是否重复登录

1、admin.php 中 route数组 middleware 添加中间件single_m
'route' => ['prefix' => env('ADMIN_ROUTE_PREFIX', 'admin'),'namespace' => 'App\\Admin\\Controllers','middleware' => ['web', 'admin', 'single_m'],
}
2、新建中间件 app/Http/Middleware/SingleAdminLogin.php
<?php

namespace App\Http\Middleware;

use Closure;
use Dcat\Admin\Admin;
use Illuminate\Support\Facades\Cache;

class SingleAdminLogin
{
/**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */ 
    public function handle($request, Closure $next){

        //判断是否重复登录if ($this->isRelogin($request)) {//重复登录 退出登录状态Admin::guard()->logout();return redirect('/admin');}

        return $next($request);}

    /**
     * 比较token,判断是否需要重新登录
     */
    protected function isRelogin($request){
        $member = $request->user('admin');
        if ($member) {
            // 获取 session 中的 token 
            $singletoken = $request->session()->get('SINGLETOKEN');      

            if ($singletoken) {
                 // 获取 time 
                $redisTime = Cache::get($member->id); 

                // 重新获取加密参数加密
                $ip = $request->getClientIp();
                $secret = md5($ip . $member->id . $redisTime);

                if ($singletoken !== $secret) {
                  return true;
                }
                return false;
            }
        }
     return false;
   }
}
3、app/Http/Kernel.php $routeMiddleware
protected $routeMiddleware = [
  'single_m' => \App\Http\Middleware\SingleAdminLogin::class,
];

转载博客:blog.csdn.net/aawuwuwuxx/article/d...