/
SessionHandler.java
1756 lines (1582 loc) · 60.4 KB
/
SessionHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.session;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.http.Syntax;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.SessionIdManager;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ScopedHandler;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.statistic.CounterStatistic;
import org.eclipse.jetty.util.statistic.SampleStatistic;
import org.eclipse.jetty.util.thread.Locker.Lock;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.util.thread.Scheduler;
import static java.lang.Math.round;
/**
* SessionHandler.
*/
@ManagedObject
public class SessionHandler extends ScopedHandler
{
static final Logger LOG = Log.getLogger("org.eclipse.jetty.server.session");
public static final EnumSet<SessionTrackingMode> DEFAULT_TRACKING = EnumSet.of(SessionTrackingMode.COOKIE,
SessionTrackingMode.URL);
/**
* Session cookie name.
* Defaults to <code>JSESSIONID</code>, but can be set with the
* <code>org.eclipse.jetty.servlet.SessionCookie</code> context init parameter.
*/
public static final String __SessionCookieProperty = "org.eclipse.jetty.servlet.SessionCookie";
public static final String __DefaultSessionCookie = "JSESSIONID";
/**
* Session id path parameter name.
* Defaults to <code>jsessionid</code>, but can be set with the
* <code>org.eclipse.jetty.servlet.SessionIdPathParameterName</code> context init parameter.
* If context init param is "none", or setSessionIdPathParameterName is called with null or "none",
* no URL rewriting will be done.
*/
public static final String __SessionIdPathParameterNameProperty = "org.eclipse.jetty.servlet.SessionIdPathParameterName";
public static final String __DefaultSessionIdPathParameterName = "jsessionid";
public static final String __CheckRemoteSessionEncoding = "org.eclipse.jetty.servlet.CheckingRemoteSessionIdEncoding";
/**
* Session Domain.
* If this property is set as a ServletContext InitParam, then it is
* used as the domain for session cookies. If it is not set, then
* no domain is specified for the session cookie.
*/
public static final String __SessionDomainProperty = "org.eclipse.jetty.servlet.SessionDomain";
public static final String __DefaultSessionDomain = null;
/**
* Session Path.
* If this property is set as a ServletContext InitParam, then it is
* used as the path for the session cookie. If it is not set, then
* the context path is used as the path for the cookie.
*/
public static final String __SessionPathProperty = "org.eclipse.jetty.servlet.SessionPath";
/**
* Session Max Age.
* If this property is set as a ServletContext InitParam, then it is
* used as the max age for the session cookie. If it is not set, then
* a max age of -1 is used.
*/
public static final String __MaxAgeProperty = "org.eclipse.jetty.servlet.MaxAge";
public static final Set<SessionTrackingMode> DEFAULT_SESSION_TRACKING_MODES =
Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList(SessionTrackingMode.COOKIE, SessionTrackingMode.URL)));
@SuppressWarnings("unchecked")
public static final Class<? extends EventListener>[] SESSION_LISTENER_TYPES =
new Class[]
{
HttpSessionAttributeListener.class,
HttpSessionIdListener.class,
HttpSessionListener.class
};
/**
* Web.xml session-timeout is set in minutes, but is stored as an int in seconds by HttpSession and
* the sessionmanager. Thus MAX_INT is the max number of seconds that can be set, and MAX_INT/60 is the
* max number of minutes that you can set.
*/
public static final java.math.BigDecimal MAX_INACTIVE_MINUTES = new java.math.BigDecimal(Integer.MAX_VALUE / 60);
static final HttpSessionContext __nullSessionContext = new HttpSessionContext()
{
@Override
public HttpSession getSession(String sessionId)
{
return null;
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Enumeration getIds()
{
return Collections.enumeration(Collections.EMPTY_LIST);
}
};
/**
* Setting of max inactive interval for new sessions
* -1 means no timeout
*/
protected int _dftMaxIdleSecs = -1;
protected boolean _httpOnly = false;
protected SessionIdManager _sessionIdManager;
protected boolean _secureCookies = false;
protected boolean _secureRequestOnly = true;
protected final List<HttpSessionAttributeListener> _sessionAttributeListeners = new CopyOnWriteArrayList<>();
protected final List<HttpSessionListener> _sessionListeners = new CopyOnWriteArrayList<>();
protected final List<HttpSessionIdListener> _sessionIdListeners = new CopyOnWriteArrayList<>();
protected ClassLoader _loader;
protected ContextHandler.Context _context;
protected SessionContext _sessionContext;
protected String _sessionCookie = __DefaultSessionCookie;
protected String _sessionIdPathParameterName = __DefaultSessionIdPathParameterName;
protected String _sessionIdPathParameterNamePrefix = ";" + _sessionIdPathParameterName + "=";
protected String _sessionDomain;
protected String _sessionPath;
protected int _maxCookieAge = -1;
protected int _refreshCookieAge;
protected boolean _nodeIdInSessionId;
protected boolean _checkingRemoteSessionIdEncoding;
protected String _sessionComment;
protected SessionCache _sessionCache;
protected final SampleStatistic _sessionTimeStats = new SampleStatistic();
protected final CounterStatistic _sessionsCreatedStats = new CounterStatistic();
public Set<SessionTrackingMode> _sessionTrackingModes;
protected boolean _usingURLs;
protected boolean _usingCookies = true;
protected Set<String> _candidateSessionIdsForExpiry = ConcurrentHashMap.newKeySet();
protected Scheduler _scheduler;
protected boolean _ownScheduler = false;
/**
* Constructor.
*/
public SessionHandler()
{
setSessionTrackingModes(DEFAULT_SESSION_TRACKING_MODES);
}
@ManagedAttribute("path of the session cookie, or null for default")
public String getSessionPath()
{
return _sessionPath;
}
@ManagedAttribute("if greater the zero, the time in seconds a session cookie will last for")
public int getMaxCookieAge()
{
return _maxCookieAge;
}
/**
* Called by the {@link SessionHandler} when a session is first accessed by a request.
*
* @param session the session object
* @param secure whether the request is secure or not
* @return the session cookie. If not null, this cookie should be set on the response to either migrate
* the session or to refresh a session cookie that may expire.
* @see #complete(HttpSession)
*/
public HttpCookie access(HttpSession session, boolean secure)
{
long now = System.currentTimeMillis();
Session s = ((SessionIf)session).getSession();
if (s.access(now))
{
// Do we need to refresh the cookie?
if (isUsingCookies() &&
(s.isIdChanged() ||
(getSessionCookieConfig().getMaxAge() > 0 && getRefreshCookieAge() > 0 &&
((now - s.getCookieSetTime()) / 1000 > getRefreshCookieAge()))))
{
HttpCookie cookie = getSessionCookie(session, _context == null ? "/" : (_context.getContextPath()), secure);
s.cookieSet();
s.setIdChanged(false);
return cookie;
}
}
return null;
}
/**
* Adds an event listener for session-related events.
*
* @param listener the session event listener to add
* Individual SessionManagers implementations may accept arbitrary listener types,
* but they are expected to at least handle HttpSessionActivationListener,
* HttpSessionAttributeListener, HttpSessionBindingListener and HttpSessionListener.
* @see #removeEventListener(EventListener)
*/
public void addEventListener(EventListener listener)
{
if (listener instanceof HttpSessionAttributeListener)
_sessionAttributeListeners.add((HttpSessionAttributeListener)listener);
if (listener instanceof HttpSessionListener)
_sessionListeners.add((HttpSessionListener)listener);
if (listener instanceof HttpSessionIdListener)
_sessionIdListeners.add((HttpSessionIdListener)listener);
addBean(listener, false);
}
/**
* Removes all event listeners for session-related events.
*
* @see #removeEventListener(EventListener)
*/
public void clearEventListeners()
{
for (EventListener e : getBeans(EventListener.class))
{
removeBean(e);
}
_sessionAttributeListeners.clear();
_sessionListeners.clear();
_sessionIdListeners.clear();
}
/**
* Call the session lifecycle listeners
*
* @param session the session on which to call the lifecycle listeners
*/
protected void callSessionDestroyedListeners(Session session)
{
if (session == null)
return;
if (_sessionListeners != null)
{
//We annoint the calling thread with
//the webapp's classloader because the calling thread may
//come from the scavenger, rather than a request thread
Runnable r = new Runnable()
{
@Override
public void run()
{
HttpSessionEvent event = new HttpSessionEvent(session);
for (int i = _sessionListeners.size() - 1; i >= 0; i--)
{
_sessionListeners.get(i).sessionDestroyed(event);
}
}
};
_sessionContext.run(r);
}
}
/**
* Call the session lifecycle listeners
*
* @param session the session on which to call the lifecycle listeners
*/
protected void callSessionCreatedListeners(Session session)
{
if (session == null)
return;
if (_sessionListeners != null)
{
HttpSessionEvent event = new HttpSessionEvent(session);
for (int i = _sessionListeners.size() - 1; i >= 0; i--)
{
_sessionListeners.get(i).sessionCreated(event);
}
}
}
protected void callSessionIdListeners(Session session, String oldId)
{
//inform the listeners
if (!_sessionIdListeners.isEmpty())
{
HttpSessionEvent event = new HttpSessionEvent(session);
for (HttpSessionIdListener l : _sessionIdListeners)
{
l.sessionIdChanged(event, oldId);
}
}
}
/**
* Called when a request is finally leaving a session.
*
* @param session the session object
*/
public void complete(HttpSession session)
{
if (LOG.isDebugEnabled())
LOG.debug("Complete called with session {}", session);
if (session == null)
return;
Session s = ((SessionIf)session).getSession();
try
{
_sessionCache.release(s.getId(), s);
}
catch (Exception e)
{
LOG.warn(e);
}
}
/**
* Called when a response is about to be committed.
* We might take this opportunity to persist the session
* so that any subsequent requests to other servers
* will see the modifications.
*/
public void commit(HttpSession session)
{
if (session == null)
return;
Session s = ((SessionIf)session).getSession();
try
{
_sessionCache.commit(s);
}
catch (Exception e)
{
LOG.warn(e);
}
}
@Deprecated
public void complete(Session session, Request baseRequest)
{
//not used
}
/*
* @see org.eclipse.thread.AbstractLifeCycle#doStart()
*/
@Override
protected void doStart() throws Exception
{
//check if session management is set up, if not set up HashSessions
final Server server = getServer();
_context = ContextHandler.getCurrentContext();
_loader = Thread.currentThread().getContextClassLoader();
synchronized (server)
{
//Get a SessionDataStore and a SessionDataStore, falling back to in-memory sessions only
if (_sessionCache == null)
{
SessionCacheFactory ssFactory = server.getBean(SessionCacheFactory.class);
setSessionCache(ssFactory != null ? ssFactory.getSessionCache(this) : new DefaultSessionCache(this));
SessionDataStore sds = null;
SessionDataStoreFactory sdsFactory = server.getBean(SessionDataStoreFactory.class);
if (sdsFactory != null)
sds = sdsFactory.getSessionDataStore(this);
else
sds = new NullSessionDataStore();
_sessionCache.setSessionDataStore(sds);
}
if (_sessionIdManager == null)
{
_sessionIdManager = server.getSessionIdManager();
if (_sessionIdManager == null)
{
//create a default SessionIdManager and set it as the shared
//SessionIdManager for the Server, being careful NOT to use
//the webapp context's classloader, otherwise if the context
//is stopped, the classloader is leaked.
ClassLoader serverLoader = server.getClass().getClassLoader();
try
{
Thread.currentThread().setContextClassLoader(serverLoader);
_sessionIdManager = new DefaultSessionIdManager(server);
server.setSessionIdManager(_sessionIdManager);
server.manage(_sessionIdManager);
_sessionIdManager.start();
}
finally
{
Thread.currentThread().setContextClassLoader(_loader);
}
}
// server session id is never managed by this manager
addBean(_sessionIdManager, false);
}
_scheduler = server.getBean(Scheduler.class);
if (_scheduler == null)
{
_scheduler = new ScheduledExecutorScheduler(String.format("Session-Scheduler-%x", hashCode()), false);
_ownScheduler = true;
_scheduler.start();
}
}
// Look for a session cookie name
if (_context != null)
{
String tmp = _context.getInitParameter(__SessionCookieProperty);
if (tmp != null)
_sessionCookie = tmp;
tmp = _context.getInitParameter(__SessionIdPathParameterNameProperty);
if (tmp != null)
setSessionIdPathParameterName(tmp);
// set up the max session cookie age if it isn't already
if (_maxCookieAge == -1)
{
tmp = _context.getInitParameter(__MaxAgeProperty);
if (tmp != null)
_maxCookieAge = Integer.parseInt(tmp.trim());
}
// set up the session domain if it isn't already
if (_sessionDomain == null)
_sessionDomain = _context.getInitParameter(__SessionDomainProperty);
// set up the sessionPath if it isn't already
if (_sessionPath == null)
_sessionPath = _context.getInitParameter(__SessionPathProperty);
tmp = _context.getInitParameter(__CheckRemoteSessionEncoding);
if (tmp != null)
_checkingRemoteSessionIdEncoding = Boolean.parseBoolean(tmp);
}
_sessionContext = new SessionContext(_sessionIdManager.getWorkerName(), _context);
_sessionCache.initialize(_sessionContext);
super.doStart();
}
/*
* @see org.eclipse.thread.AbstractLifeCycle#doStop()
*/
@Override
protected void doStop() throws Exception
{
// Destroy sessions before destroying servlets/filters see JETTY-1266
shutdownSessions();
_sessionCache.stop();
if (_ownScheduler && _scheduler != null)
_scheduler.stop();
_scheduler = null;
super.doStop();
_loader = null;
}
/**
* @return true if session cookies should be HTTP-only (Microsoft extension)
* @see org.eclipse.jetty.http.HttpCookie#isHttpOnly()
*/
@ManagedAttribute("true if cookies use the http only flag")
public boolean getHttpOnly()
{
return _httpOnly;
}
/**
* @return The sameSite setting for session cookies or null for no setting
* @see HttpCookie#getSameSite()
*/
@ManagedAttribute("SameSite setting for session cookies")
public HttpCookie.SameSite getSameSite()
{
return HttpCookie.getSameSiteFromComment(_sessionComment);
}
/**
* Returns the <code>HttpSession</code> with the given session id
*
* @param extendedId the session id
* @return the <code>HttpSession</code> with the corresponding id or null if no session with the given id exists
*/
protected HttpSession getHttpSession(String extendedId)
{
String id = getSessionIdManager().getId(extendedId);
Session session = getSession(id);
if (session != null && !session.getExtendedId().equals(extendedId))
session.setIdChanged(true);
return session;
}
/**
* Gets the cross context session id manager
*
* @return the session id manager
*/
@ManagedAttribute("Session ID Manager")
public SessionIdManager getSessionIdManager()
{
return _sessionIdManager;
}
/**
* @return the max period of inactivity, after which the session is invalidated, in seconds.
* @see #setMaxInactiveInterval(int)
*/
@ManagedAttribute("default maximum time a session may be idle for (in s)")
public int getMaxInactiveInterval()
{
return _dftMaxIdleSecs;
}
@ManagedAttribute("time before a session cookie is re-set (in s)")
public int getRefreshCookieAge()
{
return _refreshCookieAge;
}
/**
* @return same as SessionCookieConfig.getSecure(). If true, session
* cookies are ALWAYS marked as secure. If false, a session cookie is
* ONLY marked as secure if _secureRequestOnly == true and it is an HTTPS request.
*/
@ManagedAttribute("if true, secure cookie flag is set on session cookies")
public boolean getSecureCookies()
{
return _secureCookies;
}
/**
* @return true if session cookie is to be marked as secure only on HTTPS requests
*/
public boolean isSecureRequestOnly()
{
return _secureRequestOnly;
}
/**
* HTTPS request. Can be overridden by setting SessionCookieConfig.setSecure(true),
* in which case the session cookie will be marked as secure on both HTTPS and HTTP.
*
* @param secureRequestOnly true to set Session Cookie Config as secure
*/
public void setSecureRequestOnly(boolean secureRequestOnly)
{
_secureRequestOnly = secureRequestOnly;
}
@ManagedAttribute("the set session cookie")
public String getSessionCookie()
{
return _sessionCookie;
}
/**
* A session cookie is marked as secure IFF any of the following conditions are true:
* <ol>
* <li>SessionCookieConfig.setSecure == true</li>
* <li>SessionCookieConfig.setSecure == false && _secureRequestOnly==true && request is HTTPS</li>
* </ol>
* According to SessionCookieConfig javadoc, case 1 can be used when:
* "... even though the request that initiated the session came over HTTP,
* is to support a topology where the web container is front-ended by an
* SSL offloading load balancer. In this case, the traffic between the client
* and the load balancer will be over HTTPS, whereas the traffic between the
* load balancer and the web container will be over HTTP."
* <p>
* For case 2, you can use _secureRequestOnly to determine if you want the
* Servlet Spec 3.0 default behavior when SessionCookieConfig.setSecure==false,
* which is:
* <cite>
* "they shall be marked as secure only if the request that initiated the
* corresponding session was also secure"
* </cite>
* <p>
* The default for _secureRequestOnly is true, which gives the above behavior. If
* you set it to false, then a session cookie is NEVER marked as secure, even if
* the initiating request was secure.
*
* @param session the session to which the cookie should refer.
* @param contextPath the context to which the cookie should be linked.
* The client will only send the cookie value when requesting resources under this path.
* @param requestIsSecure whether the client is accessing the server over a secure protocol (i.e. HTTPS).
* @return if this <code>SessionManager</code> uses cookies, then this method will return a new
* {@link Cookie cookie object} that should be set on the client in order to link future HTTP requests
* with the <code>session</code>. If cookies are not in use, this method returns <code>null</code>.
*/
public HttpCookie getSessionCookie(HttpSession session, String contextPath, boolean requestIsSecure)
{
if (isUsingCookies())
{
String sessionPath = (_cookieConfig.getPath() == null) ? contextPath : _cookieConfig.getPath();
sessionPath = (StringUtil.isEmpty(sessionPath)) ? "/" : sessionPath;
String id = getExtendedId(session);
HttpCookie cookie = null;
cookie = new HttpCookie(
getSessionCookieName(_cookieConfig),
id,
_cookieConfig.getDomain(),
sessionPath,
_cookieConfig.getMaxAge(),
_cookieConfig.isHttpOnly(),
_cookieConfig.isSecure() || (isSecureRequestOnly() && requestIsSecure),
HttpCookie.getCommentWithoutAttributes(_cookieConfig.getComment()),
0,
HttpCookie.getSameSiteFromComment(_cookieConfig.getComment()));
return cookie;
}
return null;
}
@ManagedAttribute("domain of the session cookie, or null for the default")
public String getSessionDomain()
{
return _sessionDomain;
}
@ManagedAttribute("number of sessions created by this node")
public int getSessionsCreated()
{
return (int)_sessionsCreatedStats.getCurrent();
}
/**
* @return the URL path parameter name for session id URL rewriting, by default "jsessionid".
* @see #setSessionIdPathParameterName(String)
*/
@ManagedAttribute("name of use for URL session tracking")
public String getSessionIdPathParameterName()
{
return _sessionIdPathParameterName;
}
/**
* @return a formatted version of {@link #getSessionIdPathParameterName()}, by default
* ";" + sessionIdParameterName + "=", for easier lookup in URL strings.
* @see #getSessionIdPathParameterName()
*/
public String getSessionIdPathParameterNamePrefix()
{
return _sessionIdPathParameterNamePrefix;
}
/**
* @return whether the session management is handled via cookies.
*/
public boolean isUsingCookies()
{
return _usingCookies;
}
/**
* @param session the session to test for validity
* @return whether the given session is valid, that is, it has not been invalidated.
*/
public boolean isValid(HttpSession session)
{
Session s = ((SessionIf)session).getSession();
return s.isValid();
}
/**
* @param session the session object
* @return the unique id of the session within the cluster (without a node id extension)
* @see #getExtendedId(HttpSession)
*/
public String getId(HttpSession session)
{
Session s = ((SessionIf)session).getSession();
return s.getId();
}
/**
* @param session the session object
* @return the unique id of the session within the cluster, extended with an optional node id.
* @see #getId(HttpSession)
*/
public String getExtendedId(HttpSession session)
{
Session s = ((SessionIf)session).getSession();
return s.getExtendedId();
}
/**
* Creates a new <code>HttpSession</code>.
*
* @param request the HttpServletRequest containing the requested session id
* @return the new <code>HttpSession</code>
*/
public HttpSession newHttpSession(HttpServletRequest request)
{
long created = System.currentTimeMillis();
String id = _sessionIdManager.newSessionId(request, created);
Session session = _sessionCache.newSession(request, id, created, (_dftMaxIdleSecs > 0 ? _dftMaxIdleSecs * 1000L : -1));
session.setExtendedId(_sessionIdManager.getExtendedId(id, request));
session.getSessionData().setLastNode(_sessionIdManager.getWorkerName());
try
{
_sessionCache.add(id, session);
Request baseRequest = Request.getBaseRequest(request);
baseRequest.setSession(session);
baseRequest.enterSession(session);
_sessionsCreatedStats.increment();
if (request != null && request.isSecure())
session.setAttribute(Session.SESSION_CREATED_SECURE, Boolean.TRUE);
callSessionCreatedListeners(session);
return session;
}
catch (Exception e)
{
LOG.warn(e);
return null;
}
}
/**
* Removes an event listener for for session-related events.
*
* @param listener the session event listener to remove
* @see #addEventListener(EventListener)
*/
public void removeEventListener(EventListener listener)
{
if (listener instanceof HttpSessionAttributeListener)
_sessionAttributeListeners.remove(listener);
if (listener instanceof HttpSessionListener)
_sessionListeners.remove(listener);
if (listener instanceof HttpSessionIdListener)
_sessionIdListeners.remove(listener);
removeBean(listener);
}
/**
* Reset statistics values
*/
@ManagedOperation(value = "reset statistics", impact = "ACTION")
public void statsReset()
{
_sessionsCreatedStats.reset();
_sessionTimeStats.reset();
}
/**
* Set if Session cookies should use HTTP Only
* @param httpOnly True if cookies should be HttpOnly.
* @see HttpCookie
*/
public void setHttpOnly(boolean httpOnly)
{
_httpOnly = httpOnly;
}
/**
* Set Session cookie sameSite mode.
* Currently this is encoded in the session comment until sameSite is supported by {@link SessionCookieConfig}
* @param sameSite The sameSite setting for Session cookies (or null for no sameSite setting)
*/
public void setSameSite(HttpCookie.SameSite sameSite)
{
// Encode in comment whilst not supported by SessionConfig, so that it can be set/saved in
// web.xml and quickstart.
// Always pass false for httpOnly as it has it's own setter.
_sessionComment = HttpCookie.getCommentWithAttributes(_sessionComment, false, sameSite);
}
/**
* @param metaManager The metaManager used for cross context session management.
*/
public void setSessionIdManager(SessionIdManager metaManager)
{
updateBean(_sessionIdManager, metaManager);
_sessionIdManager = metaManager;
}
/**
* Sets the max period of inactivity, after which the session is invalidated, in seconds.
*
* @param seconds the max inactivity period, in seconds.
* @see #getMaxInactiveInterval()
*/
public void setMaxInactiveInterval(int seconds)
{
_dftMaxIdleSecs = seconds;
if (LOG.isDebugEnabled())
{
if (_dftMaxIdleSecs <= 0)
LOG.debug("Sessions created by this manager are immortal (default maxInactiveInterval={})", _dftMaxIdleSecs);
else
LOG.debug("SessionManager default maxInactiveInterval={}", _dftMaxIdleSecs);
}
}
public void setRefreshCookieAge(int ageInSeconds)
{
_refreshCookieAge = ageInSeconds;
}
public void setSessionCookie(String cookieName)
{
_sessionCookie = cookieName;
}
/**
* Sets the session id URL path parameter name.
*
* @param param the URL path parameter name for session id URL rewriting (null or "none" for no rewriting).
* @see #getSessionIdPathParameterName()
* @see #getSessionIdPathParameterNamePrefix()
*/
public void setSessionIdPathParameterName(String param)
{
_sessionIdPathParameterName = (param == null || "none".equals(param)) ? null : param;
_sessionIdPathParameterNamePrefix = (param == null || "none".equals(param))
? null : (";" + _sessionIdPathParameterName + "=");
}
/**
* @param usingCookies The usingCookies to set.
*/
public void setUsingCookies(boolean usingCookies)
{
_usingCookies = usingCookies;
}
/**
* Get a known existing session
*
* @param id The session ID stripped of any worker name.
* @return A Session or null if none exists.
*/
public Session getSession(String id)
{
try
{
Session session = _sessionCache.get(id);
if (session != null)
{
//If the session we got back has expired
if (session.isExpiredAt(System.currentTimeMillis()))
{
//Expire the session
try
{
session.invalidate();
}
catch (Exception e)
{
LOG.warn("Invalidating session {} found to be expired when requested", id);
LOG.warn(e);
}
return null;
}
session.setExtendedId(_sessionIdManager.getExtendedId(id, null));
}
return session;
}
catch (UnreadableSessionDataException e)
{
LOG.warn("Error loading session {}", id);
LOG.warn(e);
try
{
//tell id mgr to remove session from all other contexts
getSessionIdManager().invalidateAll(id);
}
catch (Exception x)
{
LOG.warn("Error cross-context invalidating unreadable session {}", id);
LOG.warn(x);
}
return null;
}
catch (Exception other)
{
LOG.warn(other);
return null;
}
}
/**
* Prepare sessions for session manager shutdown
*
* @throws Exception if unable to shutdown sesssions
*/
protected void shutdownSessions() throws Exception
{
_sessionCache.shutdown();
}
/**
* @return the session store
*/
public SessionCache getSessionCache()
{
return _sessionCache;
}
/**
* @param cache the session store to use
*/
public void setSessionCache(SessionCache cache)
{
updateBean(_sessionCache, cache);
_sessionCache = cache;
}
/**
* @return true if the cluster node id (worker id) is returned as part of the session id by {@link HttpSession#getId()}. Default is false.
*/
public boolean isNodeIdInSessionId()
{
return _nodeIdInSessionId;
}
/**
* @param nodeIdInSessionId true if the cluster node id (worker id) will be returned as part of the session id by {@link HttpSession#getId()}. Default is false.
*/
public void setNodeIdInSessionId(boolean nodeIdInSessionId)
{
_nodeIdInSessionId = nodeIdInSessionId;
}
/**
* Remove session from manager