第 1 步:为共享会话数据设置会话驱动程序
首先,将会话驱动程序设置为跨两个域共享的数据库或缓存。您的会话驱动程序不能是文件
第 2 步:实施跨域会话 ID
会话 id 由 Laravel 中的 cookie 传递。由于您的网站位于不同的域中,因此会话 cookie 不会转移。解决此问题的一种方法是将它们附加到所有请求的查询字符串中,如下所示:domain2.tld/?session_token=abcds2342
在您的代码中必须有一些登录来检测会话,然后查询数据库/缓存(您的会话驱动程序)以获取结果。如果找到结果,则手动设置会话 ID 并启动会话:
session_id('abcds2342');
session_start();
仔细检查 IP 地址和会话 ID
防止人们猜测别人的 SessionID 从而
以其他人身份登录
第 2A 步:为此,您可以实现一个覆盖 StartSession 的自定义中间件。这个中间件应该覆盖 getSession 并且在它检查 cookie 中的 session_id 之前,检查请求中是否存在令牌。示例代码如下:
<?php
namespace App\Http\Middleware;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Http\Request;
use App\SessionShare;
use Closure;
class StartSessionWithSharer extends StartSession
{
/**
* Get the session implementation from the manager.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Session\SessionInterface
*/
public function getSession(Request $request)
{
$session = $this->manager->driver();
/**
* Check if we can find a valid session token from saved records
*/
if($request->get('session_token') && !empty($request->get('session_token'))) {
$sessionShare = SessionShare::valid()->whereToken($request->get('session_token'))->first();
if($sessionShare)
$session_id = $sessionShare->session_id;
}
/**
* Fallback to session in browser
*/
if(!isset($session_id) || !$session_id)
$session_id = $request->cookies->get($session->getName());
$session->setId($session_id);
return $session;
}
}
第 2B 步:然后创建一个自定义服务提供者来覆盖 SessionServiceProvider,如下所示:
<?php namespace App\Providers;
class CustomSessionServiceProvider extends \Illuminate\Session\SessionServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerSessionManager();
$this->registerSessionDriver();
$this->app->singleton('App\Http\Middleware\StartSessionWithSharer');
}
}
然后从 config/app.php 中删除旧的 SessionServiceProvider 并改用上面的方法。
第 2C 步:然后为表创建 App\SessionShare 模型以存储会话 ID。此外,上面的代码不负责检查 IP 地址,因此您必须添加它以使其安全并防止暴力攻击
第 2D 步:哦,最后别忘了为所有请求附加 session_token 的 get 参数
请注意,上述实现是针对数据库会话驱动程序的。当然,您也可以对缓存驱动程序执行此操作。唯一会改变的是模型实现(步骤 2C)来验证会话