Introduce
使用Session代替Token进行前后端交互,可以正常使用Session功能且兼容Session所有驱动方式。只需要替换掉StartSession中间件即可。
<?php
/*
* Copyright (c) 2025. Jerry midsmr@qq.com.
*/
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 as SymfonyResponse;
class StartSessionMiddleware 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->headers->get('x-session-id', '');
return tap(parent::handle($request, $next), function ($response) {
$response->headers->set('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(SymfonyResponse $response, Session $session)
{
}
}