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()
})
Related
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.
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).
This is the controller:
rusty = require('rusty')
module.exports =
index: (req, res)->
console.log('submit', req.session)
res.json({})
captcha: (req, res)->
_ref = rusty.captcha({
width: 120
height: 50
chars: 'abcdefghijklmnopqrstuvwxyz0123456789'
length: 4
fonts: ['20px sans', '20px bold sans']
noise: 50
})
canvas = _ref.canvas
code = _ref.code
req.session.captcha = code
return canvas.toBuffer (err, buffer)->
return res.end(buffer)
I have a route to captcha.png that calls the captcha method here. An image src is set to captcha.png. I expect that when the captcha method is called, req.session.captcha is set and I can use it to verify the form in the index method.
However, on first page load after restarting the server, the session variable is not set. If I do a subsequent call to the captcha method, then the session variable is set and can be used.
I'm assuming this has to do with the session cookie not set yet? Or is there something else I'm overlooking?
Any thoughts?
Ah, just a development issue. The fact that I already had a cookie set from a previous session, would invalidate the session on the request. Effectively, storing the variable under the wrong session. If I delete my cookie after a server restart, then all is well on page refresh.
Leaving here for anyone else scratching their head.
I try to understand this Login example.
There is a procedure called "checkWithServerIfSessionIdIsStillLegal".
I am wondering how the server can validate if a session is still valid because the session id is always different when the user closes the browser.
Can someone explain me how does this work?
By setting session id in onModule load(when he logs in) as a cookie and checking again after he accessing login page.
String sessionID = result.getSessionId();
final long DURATION = 1000 * 60 * 60 * 24 * 1;
Date expires = new Date(System.currentTimeMillis() + DURATION);
Cookies.setCookie("sid", sessionID, expires, null, "/", false);
Here is the complete implemetation of checkWithServerIfSessionIdIsStillLegal(),which you are referring.
Take a look at the following link.
Cannot use same cookie for multiple GWT applications
This might solve your problem.
I'm working on a blue green pattern for a system with continuous delivery. I would like to force the users to switch server after 30 min. I'm developing my application in JSF 2. Is there an easy way to make the sessions end after a certain time no matter if the user is active or not?
Implement a filter which does basically the following job:
HttpSession session = request.getSession();
if (session.isNew()) {
session.setAttribute("start", System.currentTimeMillis());
}
else {
long start = (Long) session.getAttribute("start");
if (System.currentTimeMillis() - start > (30 * 60 * 1000)) {
session.invalidate();
response.sendRedirect("expired.xhtml");
return;
}
}
chain.doFilter(request, response);
Map this on the servlet name or URL pattern of interest.
This is only sensitive to changes in system clock, make sure that your server runs UTC all the time. Otherwise better grab System#nanoTime() instead.