Laravel customized session.lifetime at user level

后端 未结 3 1847
刺人心
刺人心 2020-12-05 12:30

I am overwriting session.timeout value in one of the middleware (for Laravel web app) but it doesn\'t seem to be affecting in terms of timing out a session. Tho

3条回答
  •  盖世英雄少女心
    2020-12-05 12:36

    Here is what worked for me (using Laravel 5.6 or 5.5) to let a user choose session duration at login time.

    Editing the lifetime of the session in Auth controller doesn't work because by then the session is already started. You need to add middleware that executes before Laravel runs its own "StartSession" middleware.

    One way is to create a cookie to store the user's lifetime length preference and use that value when setting the session expiration on each request.

    1. New file: app/Http/Middleware/SetSessionLength.php
    namespace App\Http\Middleware;
    
    use Illuminate\Support\Facades\Cookie;
    
    class SetSessionLength {
    
        const SESSION_LIFETIME_PARAM = 'sessionLifetime';
        const SESSION_LIFETIME_DEFAULT_MINS = 5;
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, $next) {
            $lifetimeMins = Cookie::get(self::SESSION_LIFETIME_PARAM, $request->input(self::SESSION_LIFETIME_PARAM)); //https://laravel.com/api/6.x/Illuminate/Support/Facades/Cookie.html#method_get
            if ($lifetimeMins) {
                Cookie::queue(self::SESSION_LIFETIME_PARAM, $lifetimeMins, $lifetimeMins); //https://laravel.com/docs/6.x/requests#cookies
                config(['session.lifetime' => $lifetimeMins]);
            }
            return $next($request);
        }
    
    }
    
    1. Modify Kernel: app/Http/Kernel.php

    Add \App\Http\Middleware\SetSessionLength::class, right before \Illuminate\Session\Middleware\StartSession::class,.

    1. Modify Config: config/session.php

    'lifetime' => env('SESSION_LIFETIME', \App\Http\Middleware\SetSessionLength::SESSION_LIFETIME_DEFAULT_MINS),

    1. Modify: resources/views/auth/login.blade.php

    To let the user chose their preferred number of minutes, add a dropdown of minutes, such as starting with

    提交评论

提交回复
热议问题