溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

laravel單點登錄怎么實現(xiàn)

發(fā)布時間:2022-06-16 10:15:30 來源:億速云 閱讀:344 作者:iii 欄目:編程語言

這篇“l(fā)aravel單點登錄怎么實現(xiàn)”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“l(fā)aravel單點登錄怎么實現(xiàn)”文章吧。

單點登錄(Single Sign On),簡稱為 SSO,是比較流行的企業(yè)業(yè)務整合的解決方案之一。SSO的定義是在多個應用系統(tǒng)中,用戶只需要登錄一次就可以訪問所有相互信任的應用系統(tǒng)。

主系統(tǒng)登錄后跳轉(zhuǎn)分系統(tǒng)不需要登錄訪問分系統(tǒng)后臺(以laravel-admin為例)

主系統(tǒng)配置:laravel單用戶登錄

分系統(tǒng)配置如下

登錄

Encore\Admin\Controllers\AuthController.php修改,可以將方法分離不在源文件上修改。

增加代碼

use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redis;

修改postLogin()方法

if ($this->guard()->attempt($credentials, $remember)) {
     
     // return $this->sendLoginResponse($request);//此注釋修改為以下
     return $this->sendLoginResponse($request,$credentials);
}

修改 sendLoginResponse()方法

protected function sendLoginResponse(Request $request,$credentials)
    {
        admin_toastr(trans('admin.login_successful'));

        $request->session()->regenerate();

        // return redirect()->intended($this->redirectPath());
        // 制作 token
         return $this->createtoken($credentials,$request);
        
    }

增加 createtoken()方法

protected function createtoken($credentials,$request){
       
        //相同局域網(wǎng)下多設備通用token 
           if(!Redis::get('STRING_SINGLETOKEN_MAJOR1_'. $credentials['username'])){
               $time = time();
                // 當前 time 存入 Redis
               Redis::set('STRING_SINGLETOKEN_MAJOR1_'. $credentials['username'], $time);
           }
           
           //局域網(wǎng)不通用 但設備使用 注釋上邊多設備使用
           //   $time = time();
           
           $time=Redis::get('STRING_SINGLETOKEN_MAJOR1_'. $credentials['username']);
           // md5 加密
           $singleToken = md5($request->getClientIp() . $credentials['username'] . $time .'cjfdm');
           Redis::set('SINGLETOKEN_MAJOR1_'. $credentials['username'],$singleToken);
           
           // 用戶信息存入 Session
           Session::put('user_login', $credentials['username']);
        
        
         return redirect()->intended($this->redirectPath())->withCookie('SINGLETOKEN', $singleToken);
    }

首先登錄成功之后, 得到目前時間戳, 通過IP, time, 查詢得出用戶的username以及唯一防盜字符串onlykey,onlykey可以為任意字符,進行 MD5 加密, 得到 TOKEN 。然后我們將剛剛得到的時間戳以及token, 存入 Redis, Redis Key 為字符串拼接上username, 方便后面中間件的 TOKEN 驗證, 然后我們把用戶信息存入 Session . 上邊與主系統(tǒng)區(qū)別,為Redis的 rediskey不同,目的主系統(tǒng)賬號被頂?shù)舻那闆r不影響分系統(tǒng)登錄

創(chuàng)建中間件

中間件通俗點說就是訪問方法時,會提前驗證中間件的內(nèi)容,驗證通過可以訪問要訪問方法

命令創(chuàng)建中間件

// 項目根目錄運行
    php artisan make:middleware SsoMiddleware

上面?zhèn)€命令會在 app/Http/Middleware下面生成一個SsoMiddleware.php 文件, 將中間件添加到app/Http/ Kernel.php

protected $routeMiddleware = []中添加以下

'SsoMiddleware' => \App\Http\Middleware\SsoMiddleware::class,

現(xiàn)在到中間件中寫程序 app/Http/Middleware/SsoMiddleware.php, 在文件中有 handle 方法, 我們在這個方法中寫邏輯.

public function handle($request, Closure $next)
    {
        
        $prefix=config('admin.route.prefix');
        $array=['/'.$prefix.'/auth/login','/'.$prefix.'/auth/logout','/'.$prefix.'/auth/clearsession'];
        $username= Session::get('user_login');
        $info=array();
        
        $info['time']=$request->input('time');
        $info['username']=$request->input('username');
        $info['token']=$request->input('token');
        if(!$info['username']||!$username){
            $url=$request->getRequestUri();
            if(in_array($url,$array)){
        
                return $next($request);
                exit;
            }
        }
       
        
        if ($username) {
            
            // 獲取 Cookie 中的 token
            $singletoken = Redis::get('SINGLETOKEN_MAJOR1_'.$username);
            if ($singletoken) {
                // 從 Redis 獲取 time
                $redisTime = Redis::get('STRING_SINGLETOKEN_MAJOR1_'. $username);
                // 重新獲取加密參數(shù)加密
                $ip = $request->getClientIp();
                $secret = md5($ip . $username . $redisTime.'cjfdm');
                if ($singletoken != $secret) {              
                    // 記錄此次異常登錄記錄
                    // \DB::table('data_login_exception')->insert(['guid' => $userInfo->guid, 'ip' => $ip, 'addtime' => time()]);
                    // 清除 session 數(shù)據(jù)
                    
                    // abort('404','你可能來到了沒有知識的荒漠');
                    // return redirect('/'.$prefix.'/auth/logout');
                    // $request->session()->invalidate();
                    $data = [
                        'message' => '您的帳號在另一個地點登錄..!',
                        'url' => '/'.$prefix.'/auth/clearsession',
                        'jumpTime' => 5,
                        'status' => 'error'
                    ];
                    //顯示模板及數(shù)據(jù)
                    return response()-> view('errors/Prompt',compact('data'));
                }
                return $next($request);
            } else {
                return redirect('/'.$prefix.'/auth/logout');
            }
        } else {
            if ($info['username']) {
                $singletoken = $info['token'];
                $redisTime =$info['time'];
                $username=$info['username'];
                $ip = $request->getClientIp();
                $secret = md5($ip . $username . $redisTime.'cjfdm');
                 if ($singletoken != $secret) {   
                     return redirect('/'.$prefix.'/auth/logout');
                 }else{
                     $remember = $request->get('remember', false);
                     
                     $credentials['username']=$info['username'];
                    
                    if (Auth::guard('admin')->attempt($credentials, $remember)) {
                        // return $this->sendLoginResponse($request);
                        $request=Request();
                        return $this->sendLoginResponse($request,$credentials);
                    }
                     
                     
                 } 
            }else{
                 return redirect('/'.$prefix.'/auth/logout');
            }
            
        }
    }

上面中間件之中做的事情是: 獲取用戶存在 Session 之中的數(shù)據(jù)作為第一重判斷, 如果通過判斷, 進入第二重判斷, 先獲取token 以及存入 Redis 的時間戳, 取出來安順序和IP,username,time,onlykey,MD5加密, 加密后和客戶端得到的token 對比. 與主系統(tǒng)區(qū)別為 分系統(tǒng)中鏈接有username 可以開啟單點登錄,如果token驗證成功可以在不知密碼情況登錄分系統(tǒng)

其中errors/Prompt為提示樣樣式需要點此下載

清除clearsession()方法

public function clearsession(Request $request){
        $prefix=config('admin.route.prefix');
       return  redirect('/'.$prefix.'/auth/logout');
}

路由組

我們邏輯寫完了, 最后一步就是將用戶登錄后的每一步操作都掌控在自己手里, 這里我們就需要路由組.

修改config/admin.php

'middleware' => ['web', 'admin','SsoMiddleware'],

還有一步主系統(tǒng)單點登錄分系統(tǒng)方法

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redis;

class SsoController extends Controller
{
    public function ssoinfo(Request $request){
        
        $data=array();
        $data['username']=Session::get('user_login');
        $data['time']=Redis::get('STRING_SINGLETOKEN_MAJOR_'. $data['username']);
       
        $data['token']=Redis::get('SINGLETOKEN_MAJOR_'.$data['username']);
        return redirect()->intended("http://activeadmin.rongdeji.com/zhuanshu/auth/login?username=".$data['username'].'&&time='.$data['time'].'&&token='.$data['token']);
    }
    
}

路由綁定后訪問ssoinfo

以上就是關(guān)于“l(fā)aravel單點登錄怎么實現(xiàn)”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI