如何设置永久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_checkbecomes 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
.envfile and updateSESSION_LIFETIMEto a higher value (e.g.,SESSION_LIFETIME=1440for 24 hours, or43200for 30 days). - If you don't use
.envfor this, editconfig/session.phpand set thelifetimekey 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); }
4. Check Browser Cookie Restrictions
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

