or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdauthorization.mdindex.mdrealms.mdsecurity-annotations.mdsecurity-manager.mdsession-management.mdsubject-operations.mdutilities.md

session-management.mddocs/

0

# Session Management

1

2

Apache Shiro provides security-aware session management that works independently of web containers, offering consistent session handling across different deployment environments. The session management framework supports custom session storage, event handling, and comprehensive session lifecycle management.

3

4

## Capabilities

5

6

### Core Session Interface

7

8

The fundamental session abstraction providing secure session operations.

9

10

```java { .api }

11

/**

12

* A Session is a security-focused time-sensitive data cache storing user application data.

13

*/

14

public interface Session {

15

/**

16

* Returns the unique identifier assigned by the system upon session creation.

17

* @return the unique identifier assigned to this session upon creation

18

*/

19

Serializable getId();

20

21

/**

22

* Returns the time the session was started; that is, the time the system created the instance.

23

* @return the time the session was started (system created the instance)

24

*/

25

Date getStartTimestamp();

26

27

/**

28

* Returns the last time the application received a request or method invocation from the user associated with this session.

29

* @return the time the user last interacted with the system

30

*/

31

Date getLastAccessTime();

32

33

/**

34

* Returns the time in milliseconds that the session session may remain idle before expiring.

35

* @return the time in milliseconds the session may remain idle before expiring

36

*/

37

long getTimeout();

38

39

/**

40

* Sets the time in milliseconds that the session may remain idle before expiring.

41

* @param maxIdleTimeInMillis the time in milliseconds that the session may remain idle before expiring

42

* @throws InvalidSessionException if the session has been stopped or expired prior to calling this method

43

*/

44

void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException;

45

46

/**

47

* Returns the host name or IP address of the host where the session originated.

48

* @return the host name or IP address of the host where the session originated

49

*/

50

String getHost();

51

52

/**

53

* Explicitly updates the lastAccessTime of this session to the current time.

54

* @throws InvalidSessionException if the session has been stopped or expired prior to calling this method

55

*/

56

void touch() throws InvalidSessionException;

57

58

/**

59

* Immediately stops this session and releases all associated resources.

60

* @throws InvalidSessionException if the session has already been stopped or expired prior to calling this method

61

*/

62

void stop() throws InvalidSessionException;

63

64

/**

65

* Returns the keys of all the attributes stored under this session.

66

* @return the keys of all attributes stored under this session

67

* @throws InvalidSessionException if the session has been stopped or expired prior to calling this method

68

*/

69

Collection<Object> getAttributeKeys() throws InvalidSessionException;

70

71

/**

72

* Returns the object bound to this session identified by the specified key.

73

* @param key the unique name of the object bound to this session

74

* @return the object bound under the specified key name or null if there is no object bound under that name

75

* @throws InvalidSessionException if the session has been stopped or expired prior to calling this method

76

*/

77

Object getAttribute(Object key) throws InvalidSessionException;

78

79

/**

80

* Binds the specified value to this session, uniquely identified by the specified key name.

81

* @param key the name under which the value object will be bound in this session

82

* @param value the value to bind to this session

83

* @throws InvalidSessionException if the session has been stopped or expired prior to calling this method

84

*/

85

void setAttribute(Object key, Object value) throws InvalidSessionException;

86

87

/**

88

* Removes (unbinds) the object bound to this session under the specified key name.

89

* @param key the name uniquely identifying the object to remove

90

* @return the object removed or null if there was no object bound under the name

91

* @throws InvalidSessionException if the session has been stopped or expired prior to calling this method

92

*/

93

Object removeAttribute(Object key) throws InvalidSessionException;

94

}

95

```

96

97

### Session Manager

98

99

Interface for managing session lifecycle and operations.

100

101

```java { .api }

102

/**

103

* A SessionManager manages the creation, maintenance, and clean-up of Sessions.

104

*/

105

public interface SessionManager {

106

/**

107

* Starts a new session based on the specified contextual initialization data.

108

* @param context the context data used to initialize the session

109

* @return the newly started Session

110

*/

111

Session start(SessionContext context);

112

113

/**

114

* Retrieves the session corresponding to the specified contextual lookup data.

115

* @param key the session key used to look up the target session

116

* @return the session identified by sessionKey

117

* @throws SessionException if there is a problem retrieving the corresponding session

118

*/

119

Session getSession(SessionKey key) throws SessionException;

120

}

121

122

/**

123

* Default SessionManager implementation providing comprehensive session management capabilities.

124

*/

125

public class DefaultSessionManager extends AbstractSessionManager implements CacheManagerAware {

126

/**

127

* The default time in milliseconds that sessions will expire (30 minutes).

128

*/

129

public static final long DEFAULT_GLOBAL_SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes

130

131

public DefaultSessionManager();

132

133

/**

134

* Sets the system-wide default session timeout value that will be applied to all sessions.

135

* @param globalSessionTimeout the system-wide session timeout value in milliseconds

136

*/

137

public void setGlobalSessionTimeout(long globalSessionTimeout);

138

139

/**

140

* Returns the system-wide default session timeout value in milliseconds.

141

* @return the system-wide default session timeout value in milliseconds

142

*/

143

public long getGlobalSessionTimeout();

144

145

/**

146

* Sets the SessionDAO used for session persistence operations.

147

* @param sessionDAO the SessionDAO to use for session persistence operations

148

*/

149

public void setSessionDAO(SessionDAO sessionDAO);

150

151

/**

152

* Returns the SessionDAO used for session persistence operations.

153

* @return the SessionDAO used for session persistence operations

154

*/

155

public SessionDAO getSessionDAO();

156

157

/**

158

* Sets whether or not session validation is enabled.

159

* @param sessionValidationSchedulerEnabled whether or not session validation should be automatically performed

160

*/

161

public void setSessionValidationSchedulerEnabled(boolean sessionValidationSchedulerEnabled);

162

163

/**

164

* Returns whether or not session validation is enabled.

165

* @return true if session validation is enabled, false otherwise

166

*/

167

public boolean isSessionValidationSchedulerEnabled();

168

169

/**

170

* Sets the time interval (in milliseconds) that the session validation process should check for expired sessions.

171

* @param sessionValidationInterval the time interval (in milliseconds) that the session validation process should check for expired sessions

172

*/

173

public void setSessionValidationInterval(long sessionValidationInterval);

174

175

/**

176

* Returns the time interval (in milliseconds) that the session validation process checks for expired sessions.

177

* @return the time interval (in milliseconds) that the session validation process checks for expired sessions

178

*/

179

public long getSessionValidationInterval();

180

181

/**

182

* Sets whether or not sessions should be automatically deleted when they are discovered to be invalid.

183

* @param deleteInvalidSessions whether or not sessions should be automatically deleted when they are discovered to be invalid

184

*/

185

public void setDeleteInvalidSessions(boolean deleteInvalidSessions);

186

187

/**

188

* Returns whether or not sessions are automatically deleted when they are discovered to be invalid.

189

* @return true if invalid sessions will be automatically deleted, false otherwise

190

*/

191

public boolean isDeleteInvalidSessions();

192

193

public Session start(SessionContext context);

194

public Session getSession(SessionKey key) throws SessionException;

195

}

196

```

197

198

**Usage Example:**

199

200

```java

201

// Configure session manager

202

DefaultSessionManager sessionManager = new DefaultSessionManager();

203

204

// Set global session timeout (2 hours)

205

sessionManager.setGlobalSessionTimeout(2 * 60 * 60 * 1000);

206

207

// Configure session validation

208

sessionManager.setSessionValidationSchedulerEnabled(true);

209

sessionManager.setSessionValidationInterval(60 * 1000); // Check every minute

210

sessionManager.setDeleteInvalidSessions(true);

211

212

// Set session storage

213

MemorySessionDAO sessionDAO = new MemorySessionDAO();

214

sessionManager.setSessionDAO(sessionDAO);

215

216

// Apply to security manager

217

DefaultSecurityManager securityManager = new DefaultSecurityManager();

218

securityManager.setSessionManager(sessionManager);

219

```

220

221

### Session Implementation

222

223

Concrete session implementation.

224

225

```java { .api }

226

/**

227

* Simple JavaBeans-compatible implementation of the Session interface.

228

*/

229

public class SimpleSession implements ValidatingSession, Serializable {

230

public SimpleSession();

231

232

/**

233

* Constructs a new SimpleSession instance with the specified host.

234

* @param host the host where the session originated

235

*/

236

public SimpleSession(String host);

237

238

public Serializable getId();

239

public Date getStartTimestamp();

240

public Date getLastAccessTime();

241

public long getTimeout();

242

public void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException;

243

public String getHost();

244

public void touch() throws InvalidSessionException;

245

public void stop() throws InvalidSessionException;

246

public Collection<Object> getAttributeKeys() throws InvalidSessionException;

247

public Object getAttribute(Object key) throws InvalidSessionException;

248

public void setAttribute(Object key, Object value) throws InvalidSessionException;

249

public Object removeAttribute(Object key) throws InvalidSessionException;

250

251

/**

252

* Returns true if this session is stopped (either expired or explicitly stopped).

253

* @return true if this session is stopped, false otherwise

254

*/

255

public boolean isStoppedOrExpired();

256

257

/**

258

* Returns true if this session has expired, false otherwise.

259

* @return true if this session has expired, false otherwise

260

*/

261

public boolean isExpired();

262

263

/**

264

* Validates this session by checking if it has stopped or expired.

265

* @throws InvalidSessionException if this session has stopped or expired

266

*/

267

public void validate() throws InvalidSessionException;

268

}

269

270

/**

271

* Interface for sessions that can validate themselves.

272

*/

273

public interface ValidatingSession extends Session {

274

/**

275

* Returns true if this session has stopped or expired, false otherwise.

276

* @return true if this session has stopped or expired, false otherwise

277

*/

278

boolean isValid();

279

280

/**

281

* Validates the session, typically by checking if it has expired or been stopped.

282

* @throws InvalidSessionException if the session is invalid

283

*/

284

void validate() throws InvalidSessionException;

285

}

286

```

287

288

### Session Context and Keys

289

290

Context objects for session creation and lookup.

291

292

```java { .api }

293

/**

294

* A SessionContext is used by SessionManager implementations to transport session creation context data.

295

*/

296

public interface SessionContext extends Map<String, Object> {

297

/**

298

* Returns the originating host name or IP address (as a String) from where the Session will be created.

299

* @return the originating host name or IP address (as a String) from where the Session will be created

300

*/

301

String getHost();

302

303

/**

304

* Sets the originating host name or IP address from where the Session will be created.

305

* @param host the originating host name or IP address from where the Session will be created

306

*/

307

void setHost(String host);

308

}

309

310

/**

311

* Default implementation of the SessionContext interface.

312

*/

313

public class DefaultSessionContext implements SessionContext {

314

public DefaultSessionContext();

315

316

/**

317

* Constructor accepting a map of session context data.

318

* @param map the map containing initial session context data

319

*/

320

public DefaultSessionContext(Map<String, Object> map);

321

322

public String getHost();

323

public void setHost(String host);

324

}

325

326

/**

327

* A SessionKey is just a marker interface that represents a key that can be used to retrieve a Session.

328

*/

329

public interface SessionKey {

330

/**

331

* Returns the session ID referenced by this SessionKey instance.

332

* @return the session ID referenced by this SessionKey instance

333

*/

334

Serializable getSessionId();

335

}

336

337

/**

338

* Default implementation of the SessionKey interface.

339

*/

340

public class DefaultSessionKey implements SessionKey {

341

public DefaultSessionKey();

342

343

/**

344

* Constructor accepting a session ID.

345

* @param sessionId the session ID

346

*/

347

public DefaultSessionKey(Serializable sessionId);

348

349

public Serializable getSessionId();

350

public void setSessionId(Serializable sessionId);

351

}

352

```

353

354

### Session Factory

355

356

Factory for creating session instances.

357

358

```java { .api }

359

/**

360

* A SessionFactory creates Session instances based on contextual information.

361

*/

362

public interface SessionFactory {

363

/**

364

* Creates a new Session instance based on the specified contextual initialization data.

365

* @param initData the initialization data to be used during Session creation

366

* @return a new Session instance

367

*/

368

Session createSession(SessionContext initData);

369

}

370

371

/**

372

* SessionFactory implementation that creates SimpleSession instances.

373

*/

374

public class SimpleSessionFactory implements SessionFactory {

375

public SimpleSessionFactory();

376

377

public Session createSession(SessionContext initData);

378

}

379

```

380

381

### Session DAO (Data Access Object)

382

383

Interface for persisting and managing session data.

384

385

```java { .api }

386

/**

387

* Data Access Object design pattern specification to enable Session access to an EIS (Enterprise Information System).

388

*/

389

public interface SessionDAO {

390

/**

391

* Inserts a new Session record into the underlying EIS.

392

* @param session the Session object to create in the EIS

393

* @return the EIS record primary key created for the new Session record

394

*/

395

Serializable create(Session session);

396

397

/**

398

* Retrieves the session from the EIS uniquely identified by the specified sessionId.

399

* @param sessionId the system-wide unique identifier of the Session object to retrieve from the EIS

400

* @return the persisted session in the EIS identified by sessionId

401

*/

402

Session readSession(Serializable sessionId) throws UnknownSessionException;

403

404

/**

405

* Updates (persists) data from a previously created Session instance in the underlying EIS.

406

* @param session the Session to update

407

* @throws UnknownSessionException if no existing EIS session record exists with the identifier of session.getId()

408

*/

409

void update(Session session) throws UnknownSessionException;

410

411

/**

412

* Deletes the associated EIS record of the specified Session instance.

413

* @param session the Session to delete

414

*/

415

void delete(Session session);

416

417

/**

418

* Returns all sessions in the EIS that are considered active.

419

* @return all sessions in the EIS that are considered active

420

*/

421

Collection<Session> getActiveSessions();

422

}

423

424

/**

425

* Simple memory-based implementation of the SessionDAO interface.

426

*/

427

public class MemorySessionDAO extends AbstractSessionDAO {

428

public MemorySessionDAO();

429

430

protected Serializable doCreate(Session session);

431

protected Session doReadSession(Serializable sessionId);

432

public void update(Session session) throws UnknownSessionException;

433

public void delete(Session session);

434

public Collection<Session> getActiveSessions();

435

}

436

437

/**

438

* SessionDAO implementation that relies on an enterprise caching product as the EIS record store.

439

*/

440

public class EnterpriseCacheSessionDAO extends CachingSessionDAO {

441

public EnterpriseCacheSessionDAO();

442

443

/**

444

* Sets the name of the cache used to store active sessions.

445

* @param activeSessionsCacheName the name of the cache used to store active sessions

446

*/

447

public void setActiveSessionsCacheName(String activeSessionsCacheName);

448

449

/**

450

* Returns the name of the cache used to store active sessions.

451

* @return the name of the cache used to store active sessions

452

*/

453

public String getActiveSessionsCacheName();

454

455

protected Serializable doCreate(Session session);

456

protected Session doReadSession(Serializable sessionId);

457

protected void doUpdate(Session session);

458

protected void doDelete(Session session);

459

}

460

461

/**

462

* Abstract SessionDAO implementation that assumes session storage in a cache or similar key/value store.

463

*/

464

public abstract class CachingSessionDAO extends AbstractSessionDAO implements CacheManagerAware {

465

public CachingSessionDAO();

466

467

/**

468

* Sets the CacheManager to use for session storage.

469

* @param cacheManager the CacheManager to use for session storage

470

*/

471

public void setCacheManager(CacheManager cacheManager);

472

473

/**

474

* Returns the CacheManager used for session storage.

475

* @return the CacheManager used for session storage

476

*/

477

public CacheManager getCacheManager();

478

}

479

```

480

481

**Usage Example:**

482

483

```java

484

// Configure different session storage options

485

486

// 1. Memory-based storage (default)

487

MemorySessionDAO memoryDAO = new MemorySessionDAO();

488

489

// 2. Enterprise cache-based storage

490

EnterpriseCacheSessionDAO cacheDAO = new EnterpriseCacheSessionDAO();

491

cacheDAO.setCacheManager(cacheManager);

492

cacheDAO.setActiveSessionsCacheName("shiro-activeSessionsCache");

493

494

// 3. Custom database storage

495

public class DatabaseSessionDAO extends AbstractSessionDAO {

496

@Override

497

protected Serializable doCreate(Session session) {

498

// Save to database and return generated ID

499

return saveToDatabase(session);

500

}

501

502

@Override

503

protected Session doReadSession(Serializable sessionId) {

504

// Load from database

505

return loadFromDatabase(sessionId);

506

}

507

508

@Override

509

public void update(Session session) throws UnknownSessionException {

510

// Update in database

511

updateInDatabase(session);

512

}

513

514

@Override

515

public void delete(Session session) {

516

// Delete from database

517

deleteFromDatabase(session);

518

}

519

520

@Override

521

public Collection<Session> getActiveSessions() {

522

// Return all active sessions from database

523

return getActiveSessionsFromDatabase();

524

}

525

}

526

```

527

528

### Session ID Generation

529

530

Interface and implementations for generating session identifiers.

531

532

```java { .api }

533

/**

534

* Interface for components that can generate session IDs.

535

*/

536

public interface SessionIdGenerator {

537

/**

538

* Generates a new ID for a new session based on the specified session creation context.

539

* @param session the new session instance for which an ID will be generated and then assigned

540

* @return the session ID to assign to the specified session instance

541

*/

542

Serializable generateId(Session session);

543

}

544

545

/**

546

* SessionIdGenerator that generates String values of Java UUIDs as session IDs.

547

*/

548

public class JavaUuidSessionIdGenerator implements SessionIdGenerator {

549

public JavaUuidSessionIdGenerator();

550

551

public Serializable generateId(Session session);

552

}

553

```

554

555

### Session Listeners

556

557

Event listeners for session lifecycle events.

558

559

```java { .api }

560

/**

561

* Interface to be implemented by components that wish to be notified of session lifecycle events.

562

*/

563

public interface SessionListener {

564

/**

565

* Notification callback that occurs when a new session has started.

566

* @param session the session that has started

567

*/

568

void onStart(Session session);

569

570

/**

571

* Notification callback that occurs when a session has been stopped, either programmatically or due to expiration.

572

* @param session the session that has stopped

573

*/

574

void onStop(Session session);

575

576

/**

577

* Notification callback that occurs when a session has expired.

578

* @param session the session that has expired

579

*/

580

void onExpiration(Session session);

581

}

582

583

/**

584

* Simple adapter implementation of the SessionListener interface that provides empty method implementations.

585

*/

586

public class SessionListenerAdapter implements SessionListener {

587

public void onStart(Session session) {}

588

public void onStop(Session session) {}

589

public void onExpiration(Session session) {}

590

}

591

```

592

593

**Usage Example:**

594

595

```java

596

// Create custom session listener

597

public class MySessionListener implements SessionListener {

598

@Override

599

public void onStart(Session session) {

600

System.out.println("Session started: " + session.getId());

601

// Log session start, initialize user activity tracking, etc.

602

}

603

604

@Override

605

public void onStop(Session session) {

606

System.out.println("Session stopped: " + session.getId());

607

// Clean up user-specific resources, log session end, etc.

608

}

609

610

@Override

611

public void onExpiration(Session session) {

612

System.out.println("Session expired: " + session.getId());

613

// Handle expired session cleanup

614

}

615

}

616

617

// Configure session manager with listener

618

DefaultSessionManager sessionManager = new DefaultSessionManager();

619

sessionManager.getSessionListeners().add(new MySessionListener());

620

```

621

622

## Exception Hierarchy

623

624

```java { .api }

625

/**

626

* Base exception for all Session-related problems.

627

*/

628

public class SessionException extends ShiroException {

629

public SessionException();

630

public SessionException(String message);

631

public SessionException(Throwable cause);

632

public SessionException(String message, Throwable cause);

633

}

634

635

/**

636

* Exception thrown when attempting to interact with an invalid session.

637

*/

638

public class InvalidSessionException extends SessionException {

639

public InvalidSessionException();

640

public InvalidSessionException(String message);

641

public InvalidSessionException(Throwable cause);

642

public InvalidSessionException(String message, Throwable cause);

643

}

644

645

/**

646

* Exception thrown when attempting to interact with a session that has been explicitly stopped.

647

*/

648

public class StoppedSessionException extends InvalidSessionException {

649

public StoppedSessionException();

650

public StoppedSessionException(String message);

651

public StoppedSessionException(Throwable cause);

652

public StoppedSessionException(String message, Throwable cause);

653

}

654

655

/**

656

* Exception thrown when attempting to interact with a session that has expired.

657

*/

658

public class ExpiredSessionException extends StoppedSessionException {

659

public ExpiredSessionException();

660

public ExpiredSessionException(String message);

661

public ExpiredSessionException(Throwable cause);

662

public ExpiredSessionException(String message, Throwable cause);

663

}

664

665

/**

666

* Exception thrown when referencing a session that cannot be found.

667

*/

668

public class UnknownSessionException extends InvalidSessionException {

669

public UnknownSessionException();

670

public UnknownSessionException(String message);

671

public UnknownSessionException(Throwable cause);

672

public UnknownSessionException(String message, Throwable cause);

673

}

674

```