Set Session Timeout Per User

You may want to set session timeout per user. For example, you may want to apply a shorter session timeout for administrative users for security reason.

We can accomplish it by using EVENT_BEFORE_REQUEST event of the application.

Write like the following in your application configuration:




    'components' => [

        ...

        'user' => [

            'identityClass' => 'app\models\User',

            'enableAutoLogin' => false,

            'authTimeout' => 60 * 20,   // default value must be set explicitly (#1)

        ],

        ...

    ],

    'on beforeRequest' => function ($event) {

        $user = Yii::$app->user;

        if (!$user->isGuest) {

            if ($user->can('administrator')) {  // Or any other logic that determines

                $user->authTimeout = 60 * 5;    // the session timeout of the users

                // update the expiration time in the session (#2)

                Yii::$app->session->set($user->authTimeoutParam, time() + $user->authTimeout);

            }

        }

    },



In the above, we set the timeout for the administrators to be 5 minutes, while that of the standard users is 20 minutes.

(#1) You have to set the default value of yii\web\User::authTimeout explicitly in the config for User component, otherwise User component will not check the expiration of the login session.

(#2) Changing authTimeout alone is not enough. You have to update the expiration time in the session, which has been already set using the default authTimeout value before you change it.

FYI, The following is for Yii 1.1.

How To Set Session Timeout Per User At Login Time?

One thing to note, is that enableAutoLogin MUST BE FALSE. The authTimeout is ignored if it is enabled!

I don’t think you need to manually calculate the time to expire. autoRenewCookie is enabled by default, so every request automatically calculates the new expiration time.

Is the beforeRequest necessary? I haven’t tested it, but have you tried something like this:




'components' => [

    ...

    'user' => [

        'identityClass' => 'app\models\User',

        'enableAutoLogin' => false,

        'authTimeout' => function () {

            $user = Yii::$app->user;

            if (!$user->isGuest && $user->can('administrator')) {

                return 60 * 5;

            }

            return 60 * 20;

        }

    ],

    ...

],



I don’t know if anonymous functions are available here in the config… but maybe this example (even if it doesn’t work) gives an idea of how to simplify your solution :)