Richer
Published on 2024-12-07 / 10 Visits
0
0

Laravel使用SessionID替代JWT Token

Introduce

使用SESSION代替Token进行前后端交互,可以正常使用SESSION功能且兼容SESSION所有驱动方式。只需要替换掉原有的SESSION驱动即可

Code

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Session\Session;
use Illuminate\Foundation\Http\Middleware\Concerns\ExcludesPaths;
use Illuminate\Http\Request;
use Illuminate\Session\Middleware\StartSession;
use Symfony\Component\HttpFoundation\Response;

class UseSessionIdMiddleware extends StartSession
{
    use ExcludesPaths;

    /**
     * 哪些地址不使用SESSION
     *
     * @var array|string[]
     */
    protected array $except = ['/'];

    protected string $sessionId = '';

    public function handle($request, Closure $next)
    {
        if ($this->inExceptArray($request)) {
            return $next($request);
        }
  
        $this->sessionId = $request->header('X-SESSION-ID', '');

        return tap(parent::handle($request, $next), function ($response) {
            $response->header('X-SESSION-ID', $this->manager->getId());
        });
    }

    public function getSession(Request $request)
    {
        return tap($this->manager->driver(), function ($session) use ($request) {
            $session->setId($this->sessionId);
        });
    }

    protected function addCookieToResponse(Response $response, Session $session)
    {
        //不响应SessionId到Cookie
    }
}

只需要替换掉StartSession中间件


Comment