You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置永久Cookie?解决Cookie登录几小时未操作自动登出问题

Alright, let's break down why your users are getting logged out after hours of inactivity even though you're using Cookie::forever(), and walk through practical fixes step by step.

Root Cause Analysis

Looking at your middleware code, the core problem lies in your authentication flow relying on both a permanent Cookie and Laravel's Session:

  • You correctly store the token in a permanent Cookie, which should persist long-term.
  • But your middleware first tries to fetch user data from the Session ($user_check = $request->session()->get('parent' . md5($token))).
  • Laravel's default Session lifetime is only 120 minutes (2 hours). Once the Session expires, $user_check becomes null.
  • If your getActiveParentAuthInfoByToken($token) method fails to retrieve the user (maybe the token itself has an expiration, or the query encounters issues), you end up redirecting to login even though the Cookie is still valid.

Step-by-Step Solutions

1. Verify Your Token's Expiration Date

First, check if the $parentsAuthenticationInfo->token itself has an expiration time. If the token is set to expire after a few hours, the permanent Cookie won't matter—once the token is invalid, your middleware will fail to fetch the user.

  • Make sure the token is generated with a long enough expiration (e.g., 30 days or more) if you want persistent login.
  • If your system requires token rotation, add logic in the middleware to refresh the token when it's close to expiring, and update the Cookie with the new token.

2. Extend Session Lifetime (If You Want to Keep Using Session)

Since your current middleware depends on Session storage, extend the Session's lifetime to match your desired inactivity period:

  • Open your .env file and update SESSION_LIFETIME to a higher value (e.g., SESSION_LIFETIME=1440 for 24 hours, or 43200 for 30 days).
  • If you don't use .env for this, edit config/session.php and set the lifetime key to your desired number of minutes.

3. Optimize Middleware to Reduce Session Dependency

The most reliable fix is to make your authentication rely directly on the token in the Cookie, rather than the Session. This way, even if the Session expires, the valid token in the Cookie will keep the user logged in. Here's a revised middleware:

public function handle($request, Closure $next) {
    // Get the token from Cookie
    $tokenJson = $request->cookie('access_token');
    
    // No Cookie found? Redirect to login
    if (!$tokenJson) {
        return redirect('/login');
    }

    $token = json_decode($tokenJson);
    // Invalid token format? Clear Cookie and redirect
    if (!$token) {
        return redirect('/login')->withCookie(Cookie::forget('access_token'));
    }

    // Fetch user directly using the token (bypass Session)
    $parentAuthInfo = $this->parentsAuthenticationInfoRepository->getActiveParentAuthInfoByToken($token);
    
    // Token is invalid? Clear Cookie and redirect
    if (!$parentAuthInfo) {
        return redirect('/login')->withCookie(Cookie::forget('access_token'));
    }

    // Share user data with request and views
    $request->merge(['parentAuth' => $parentAuthInfo]);
    View::share(['parentAuth' => $parentAuthInfo]);
    
    return $next($request);
}

Sometimes browsers or third-party extensions can clear Cookies automatically:

  • Ensure users aren't using "incognito/private mode" (these clear Cookies when the window closes).
  • Advise users to check their browser settings to make sure your app's Cookies aren't being deleted after inactivity.

Final Notes

By focusing on the token's validity and reducing reliance on Session, you'll fix the auto-logout issue. Start with verifying the token's expiration, then adjust the middleware to use the token directly—this is the most robust approach for persistent login.

内容的提问来源于stack exchange,提问作者Gen Fa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:14:19