I am using laravel 6.I Want my laravel CSRF Token expire in every 60 seconds.
config/session
'lifetime' => 60,
First of All, CSRF is stored in XSRF-TOKEN cookie. Ref: 50904763
According to the question (Ref: 51615122), We change the configuration in app/Http/Middleware/VerifyCsrfToken.php by adding a new method named addCookieToResponse
use Symfony\Component\HttpFoundation\Cookie;
public function addCookieToResponse($request, $response) {
$config = config('session');
$session_life = env('CSRF_LIFE');
$response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), $this->availableAt($session_life),
$config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
)
);
}
where $config is used to get session information from existing lifetime. However, I parse $session_life from .env to make sure you can customize as much as you can.
So, the result is simple, configure everything as belongs but in area $this->availableAt($session_life) where session_life is in seconds.
So, please set session_life to 60 in .env as below:
CSRF_LIFE="60"
After you save and refresh your page, or clean cache and configs, Session LifeTime will be two hours but CSRF will be only 60 secs.
Hope this works.
After long testing I end up something, that you put in the lifetime option in session not allow to set expire time in seconds, it'll allow to minutes.
So, when you set up liftime = "60", it's means it will expire in 1 hour.
Hence, You have to set liftime = "1" in your config/session.pph file. Also, default value in .env file SESSION_LIFETIME=120 you have to replace that with 1 SESSION_LIFETIME = 1.
After that you have to clear the cache by command:-
php artisan config:cache
Now, your session will expire after 1 minute / 60 seconds.
To see more check this question.
Related
User's in Yii appear to be logged out automatically if they close their browser or are idle for about a day (maybe less, I'm not sure). Is it possible to not log them out ever (or at least for a long time for month or year). Not sure if the Session parameters or Cookie parameters need to change.
I've tried changing the parameters.
'components' => [
'session'=>[
'class' => 'yii\web\Session',
'cookieParams' => ['httponly' => true, 'lifetime' => 3600 * 4* 365],
'timeout' => 3600*4 *365,
'useCookies' => true
],
]
I've tried session php ini parameters:
session_set_cookie_params(0);
ini_set('session.gc_maxlifetime', 0);
And I've tried setting the login parameters
Yii::$app->user->login($user, 31536000);
The options you used it should work without timeout and useCookies options, I used it in my last project where the session needed to last for a week minimum, open storage tab in the Mozilla dev bar and click on cookies on the left you will see the cookies section with the cookies registered for your site, in my case it is http://www.kp2.local
if you use the 'lifetime' => 7 * 24 * 60 * 60, it should show the cookie with an expiry date 1 week later i.e Wed, 23 Jan 2019 like below
and if you comment out the code and then log out, and log in again it should show you the expiry time on Session like
You just need to use the following settings in the config
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
'cookieParams' => [
'httpOnly' => true,
'lifetime' => 7 * 24 * 60 * 60
],
],
If it still doesn't work, log out of the system try removing all cookies once by selecting Delete all option like in the image below.
and it will work.
Note: You should change the 7 in 'lifetime' => 7 * 24 * 60 * 60, to the number of days you want to keep the session
Keeping session for such long time may be a bad idea - inactive sessions data will consume your server resources and may slow down some operations. Yii has dedicated feature for such cases - you may set $enableAutoLogin to true:
'user' => [
'enableAutoLogin' => true,
// ...
],
And on login() call set timeout for identity cookie:
Yii::$app->user->login($user, 31536000);
It will set special cookie (valid for a year) with identity info, which will autologin user after his session expires. In this way you don't need to keep session data on your server for a year, but from user perspective it looks like he is always login (even if in the background a new session is created).
I'm currently migrating an Express single sign on application to a new identity provider. This new IdP requires the following session standards.
Session timeout: 1 hour
Session lifetime: 3 hours
If I'm interpreting this correctly the session should terminate after 1 consecutive hour of idle time or 3 hours after the session was initially generated, whichever occurs first. The relevant npm packages being used are express-session 1.15.6 and connect-mongo 2.0.1. At this point I've been able to achieve both these session parameters, but not simultaneously. I can either...
Implement 1 hour session timeout by setting session cookie maxAge to 1 hour and session rolling to true, thus resetting the cookie expires field with every response. As stated in connect-mongo if a cookie has an expiry it's applied to the session ttl field. So renewing the cookie effectively renews the session indefinitely as long as the timeout doesn't occur.
Implement 3 hour session lifetime by setting session cookie maxAge to 3 hours and session rolling to false. Now the session ttl isn't reset with every response and 3 hours after the session was created it will be terminated.
As stated above, I can't get both of these working at the same time. Any insight would be helpful as I have very little web dev experience. I've researched changing the index TTL which gave me some initial hope. I believed I could add another date field to the session object which wasn't dependent on the session cookie expires value, a createdAt date. I could then use the cookie expires as the timeout component and the createdAt date for the lifetime component. Unfortunately I'm having no luck adding this value to the session object. Am I overlooking an obvious express session option or connect-mongo setting which would solve my problem?
app.use(session({
secret: keys.expressSession.pw,
saveUninitialized: false, // don't create a session for anonymous users
resave: false, // save the session to store even if it hasn't changed
rolling: true, // reset expiration on every response
name: "definitely not a connect cookie",
cookie: {
httpOnly: true,
maxAge: 60*1000, // one minute timeout
//maxAge: 180*1000 // three minute lifetime
secure: false // https only, when true add proxy trust
},
store: new MongoStore({
url:keys.mongodb.dbURI,
// ttl: value of cookie maxAge, set redundantly in case cookie has no expiry
})
}));
I don't have time to test anything, but maybe this helps to point you in the right direction.
It is possible to change the cookie.maxAge per request, so you could calculate the maxAge every time.
From express-session docs
Alternatively req.session.cookie.maxAge will return the time remaining in milliseconds, which we may also re-assign a new value to adjust the .expires property appropriately.
So a middleware could look something like this
app.use(function (req, res, next) {
const hour = 3600
const threeHours = hour * 3
const creationDate = req.session.createdAt // set this when the session is initialized
const expires = creationDate + threeHours // expiration date
const ttl = expires - Date.now() // maximum time to life
if (ttl < hour) {
// if the maximum time to live is less than the one hour timeout, use it as maxAge
req.session.cookie.maxAge = ttl
} else {
// otherwise just stick with the "idle" timeout of 1 hour
req.session.cookie.maxAge = hour
}
next()
})
I do not want the user to be logged out of the site even if the person is idle for, it is okay if the person is logged out if he has closed the browser.
session.gc_maxlifetime = 180000
session.gc_probability = 1
session.gc_divisor = 1
session.save_path = "/var/lib/php/session"
cookie_lifetime = 0
Is there any setting that i am missing?
Please help
To set the life time i have added the following code.
session_set_cookie_params(21600);
session_start();
You need extend your live time of cookie, remember that session id is stored in user webbrowser within cookie, set session.cookie_lifetime with a more big value too.
session_set_cookie_params(21600);
session_start();
21600 seconds is only 6 hours
Try setting to something bigger maybe even PHP_INT_MAX
Dont know whether it will help just wrote to give u the idea of how?....cookie are saved at user browser so ,
$cookieName = "userscookie";
$lifetime = time() + (60*60*24); // one day life
if(isset($_COOKIE[$cookieName])) {
$value = $_COOKIE[$cookieName];
// one day life from day of access
setcookie($cookieName, $value, $lifetime);
} else {
$value = "this value to store";
setcookie($cookieName, $value, $lifetime);
}
output:
Thankyou
What I want to do is to cache a page for 1 hour. The thing is that I want to be able to set the case stale during this 1 hour period if my object is modified.
Here is my code so far:
$response = new Response();
$response->setLastModified(new \DateTime($lastModified));
if ($response->isNotModified($this->getRequest()))
return $response;
else
$response->setCache(array(
'public' => true,
'max_age' => 3600,
's_maxage' => 3600,
));
The problem is the above code doesn't check lastModified. Once the 1 hour cache is created I have to wait full 60 minutes to see the changes I have made to my object ($lastModified).
Here is an example of caching page using Last-Modified header at the symfony2 documentation.
I think your mistake is that you tries to use Last-Modified and then rewrite it with Cache-Control header (max_age, s_maxage).
This question already has an answer here:
Duplicate DB sessions created upon Zend_Auth login
(1 answer)
Closed 2 years ago.
I'm trying to store sessions in a database using Zend Sessions however for some reason my sessions die out. Im not sure if there's some code being executed which does this or whether its something else.
I've noticed that the session ID seems to be regenerated after a breif time after having logged in.
This is even despite having added the following line in my htaccess file:
php_value session.auto_start 0
The end result is that I'm logged out every minute I'm logged in.
Heres my code in my bootstrap file
$config = array(
'name' => 'session',
'primary' => 'id',
'modifiedColumn' => 'modified',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime'
);
$saveHandler = new Zend_Session_SaveHandler_DbTable($config);
Zend_Session::rememberMe($seconds = (60 * 60 * 24 * 30));
$saveHandler->setLifetime($seconds)->setOverrideLifetime(true);
Zend_Session::setSaveHandler($saveHandler);
//start your session!
Zend_Session::start();
I'm not using any other session related function except perhaps for Zend_Auth when logging in.
Infact rememberme calls the regenerateID function of the Session class - the end result is that I'm constantly logged out every few minutes now.
I think that you might be having this problem because you're calling rememberMe BEFORE starting the session.
You have to start the session first otherwise rememberMe won't do anything since it needs a session to set the rememberMe time on.
rememberMe calls the regenerateId function and the regeneration of the Id is what really needs the session to exist.
Place the rememberMe call after the session start then see how that works for you.
If that isn't it then I don't know what it could be since my code looks similar to yours.
Have you tried something like this?
protected function _initSession() {
$config = array(
'name' => 'session',
'primary' => 'id',
'modifiedColumn' => 'modified',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime',
'lifetime' => 60*60*24*30,
);
Zend_Session::setSaveHandler(new F_Session_SaveHandler_DbTable($config));
}
This way the lifetime isn't set after initialising the database sessions, but is directly included in the initialisation options - it works for me, I see no reason why this should fail in your case :).
I think you need to look once into following values after bootstrap code
session.gc_maxlifetime
session.cookie_lifetime
If You configure session resources in *.ini config file, check resources.session.cookie_domain parameter.
I spend 3 hours when I remembered about it.