laravel_admin 單一登入的簡單實現

Wen1109發表於2021-05-20

一、修改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...

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章