Laravel 5.6 基于会话令牌身份验证的购物车问题

Laravel 5.6 shopping cart based on session token authentication issue

我基于 laravel 创建了一个自定义电子商务系统。购物车由 laravel (session['_token']) 的会话令牌标识,并分为 cart table 和 cartProduct table.整个系统按预期工作。

不幸的是,一旦用户成功登录,session['_token'] 就会改变。在此之后,旧会话的整个购物车都无法正确识别,因为令牌已更改。

现在我的问题:

如果您需要有关系统的更多信息,请在评论中告诉我,我会为您提供详细信息。

购物车 - table

cart_products - table:

我找到了可行的解决方案。我修改了 LoginController 并根据需要更新了 sendLoginResponse 方法:

protected function sendLoginResponse(Request $request)
    {
        // save old session token (shopping cart is related to this one)

        $old_session_token = session()->get('_token');

        // regenerate new session (prevent session fixation)
        $request->session()->regenerate();

        // get new session token
        $new_session_token = session()->get('_token');

        // update session token in cart table

        $shopping_cart = Cart::where('session_token', $old_session_token)->first();

        $shopping_cart->session_token = $new_session_token;

        $shopping_cart->save();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }

此代码用新令牌更新旧令牌。

尝试登录前安全旧会话 ID 的主要思想

  1. 更改路线中的动作名称

    Route::post("/login", 'LoginController@doLogin');
    
  2. 修改登录控制器

    class LoginController extends Controller {
    
       use AuthenticatesUsers;
    
       private $old_session_id;
    
       public function doLogin(Request $request) {
         //remember old session id
         $this->old_session_id = $request->session()->getId();
    
         //call AuthenticatesUsers trait method
         return $this->login($request);
       }
    
       //override trait method
       protected function authenticated(Request $request, $user) {
          //sync cart
          $cart = Cart::whereSessionId($this->old_session_id)->first();
       }
    
    }