CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-apache-shiro--shiro-core

A powerful and flexible open-source Java security framework providing authentication, authorization, session management, and cryptographic services

Pending
Overview
Eval results
Files

session-management.mddocs/

Session Management

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.

Capabilities

Core Session Interface

The fundamental session abstraction providing secure session operations.

/**
 * A Session is a security-focused time-sensitive data cache storing user application data.
 */
public interface Session {
    /**
     * Returns the unique identifier assigned by the system upon session creation.
     * @return the unique identifier assigned to this session upon creation
     */
    Serializable getId();

    /**
     * Returns the time the session was started; that is, the time the system created the instance.
     * @return the time the session was started (system created the instance)
     */
    Date getStartTimestamp();

    /**
     * Returns the last time the application received a request or method invocation from the user associated with this session.
     * @return the time the user last interacted with the system
     */
    Date getLastAccessTime();

    /**
     * Returns the time in milliseconds that the session session may remain idle before expiring.
     * @return the time in milliseconds the session may remain idle before expiring
     */
    long getTimeout();

    /**
     * Sets the time in milliseconds that the session may remain idle before expiring.
     * @param maxIdleTimeInMillis the time in milliseconds that the session may remain idle before expiring
     * @throws InvalidSessionException if the session has been stopped or expired prior to calling this method
     */
    void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException;

    /**
     * Returns the host name or IP address of the host where the session originated.
     * @return the host name or IP address of the host where the session originated
     */
    String getHost();

    /**
     * Explicitly updates the lastAccessTime of this session to the current time.
     * @throws InvalidSessionException if the session has been stopped or expired prior to calling this method
     */
    void touch() throws InvalidSessionException;

    /**
     * Immediately stops this session and releases all associated resources.
     * @throws InvalidSessionException if the session has already been stopped or expired prior to calling this method
     */
    void stop() throws InvalidSessionException;

    /**
     * Returns the keys of all the attributes stored under this session.
     * @return the keys of all attributes stored under this session
     * @throws InvalidSessionException if the session has been stopped or expired prior to calling this method
     */
    Collection<Object> getAttributeKeys() throws InvalidSessionException;

    /**
     * Returns the object bound to this session identified by the specified key.
     * @param key the unique name of the object bound to this session
     * @return the object bound under the specified key name or null if there is no object bound under that name
     * @throws InvalidSessionException if the session has been stopped or expired prior to calling this method
     */
    Object getAttribute(Object key) throws InvalidSessionException;

    /**
     * Binds the specified value to this session, uniquely identified by the specified key name.
     * @param key the name under which the value object will be bound in this session
     * @param value the value to bind to this session
     * @throws InvalidSessionException if the session has been stopped or expired prior to calling this method
     */
    void setAttribute(Object key, Object value) throws InvalidSessionException;

    /**
     * Removes (unbinds) the object bound to this session under the specified key name.
     * @param key the name uniquely identifying the object to remove
     * @return the object removed or null if there was no object bound under the name
     * @throws InvalidSessionException if the session has been stopped or expired prior to calling this method
     */
    Object removeAttribute(Object key) throws InvalidSessionException;
}

Session Manager

Interface for managing session lifecycle and operations.

/**
 * A SessionManager manages the creation, maintenance, and clean-up of Sessions.
 */
public interface SessionManager {
    /**
     * Starts a new session based on the specified contextual initialization data.
     * @param context the context data used to initialize the session
     * @return the newly started Session
     */
    Session start(SessionContext context);

    /**
     * Retrieves the session corresponding to the specified contextual lookup data.
     * @param key the session key used to look up the target session
     * @return the session identified by sessionKey
     * @throws SessionException if there is a problem retrieving the corresponding session
     */
    Session getSession(SessionKey key) throws SessionException;
}

/**
 * Default SessionManager implementation providing comprehensive session management capabilities.
 */
public class DefaultSessionManager extends AbstractSessionManager implements CacheManagerAware {
    /**
     * The default time in milliseconds that sessions will expire (30 minutes).
     */
    public static final long DEFAULT_GLOBAL_SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes

    public DefaultSessionManager();

    /**
     * Sets the system-wide default session timeout value that will be applied to all sessions.
     * @param globalSessionTimeout the system-wide session timeout value in milliseconds
     */
    public void setGlobalSessionTimeout(long globalSessionTimeout);

    /**
     * Returns the system-wide default session timeout value in milliseconds.
     * @return the system-wide default session timeout value in milliseconds
     */
    public long getGlobalSessionTimeout();

    /**
     * Sets the SessionDAO used for session persistence operations.
     * @param sessionDAO the SessionDAO to use for session persistence operations
     */
    public void setSessionDAO(SessionDAO sessionDAO);

    /**
     * Returns the SessionDAO used for session persistence operations.
     * @return the SessionDAO used for session persistence operations
     */
    public SessionDAO getSessionDAO();

    /**
     * Sets whether or not session validation is enabled.
     * @param sessionValidationSchedulerEnabled whether or not session validation should be automatically performed
     */
    public void setSessionValidationSchedulerEnabled(boolean sessionValidationSchedulerEnabled);

    /**
     * Returns whether or not session validation is enabled.
     * @return true if session validation is enabled, false otherwise
     */
    public boolean isSessionValidationSchedulerEnabled();

    /**
     * Sets the time interval (in milliseconds) that the session validation process should check for expired sessions.
     * @param sessionValidationInterval the time interval (in milliseconds) that the session validation process should check for expired sessions
     */
    public void setSessionValidationInterval(long sessionValidationInterval);

    /**
     * Returns the time interval (in milliseconds) that the session validation process checks for expired sessions.
     * @return the time interval (in milliseconds) that the session validation process checks for expired sessions
     */
    public long getSessionValidationInterval();

    /**
     * Sets whether or not sessions should be automatically deleted when they are discovered to be invalid.
     * @param deleteInvalidSessions whether or not sessions should be automatically deleted when they are discovered to be invalid
     */
    public void setDeleteInvalidSessions(boolean deleteInvalidSessions);

    /**
     * Returns whether or not sessions are automatically deleted when they are discovered to be invalid.
     * @return true if invalid sessions will be automatically deleted, false otherwise
     */
    public boolean isDeleteInvalidSessions();

    public Session start(SessionContext context);
    public Session getSession(SessionKey key) throws SessionException;
}

Usage Example:

// Configure session manager
DefaultSessionManager sessionManager = new DefaultSessionManager();

// Set global session timeout (2 hours)
sessionManager.setGlobalSessionTimeout(2 * 60 * 60 * 1000);

// Configure session validation
sessionManager.setSessionValidationSchedulerEnabled(true);
sessionManager.setSessionValidationInterval(60 * 1000); // Check every minute
sessionManager.setDeleteInvalidSessions(true);

// Set session storage
MemorySessionDAO sessionDAO = new MemorySessionDAO();
sessionManager.setSessionDAO(sessionDAO);

// Apply to security manager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
securityManager.setSessionManager(sessionManager);

Session Implementation

Concrete session implementation.

/**
 * Simple JavaBeans-compatible implementation of the Session interface.
 */
public class SimpleSession implements ValidatingSession, Serializable {
    public SimpleSession();

    /**
     * Constructs a new SimpleSession instance with the specified host.
     * @param host the host where the session originated
     */
    public SimpleSession(String host);

    public Serializable getId();
    public Date getStartTimestamp();
    public Date getLastAccessTime();
    public long getTimeout();
    public void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException;
    public String getHost();
    public void touch() throws InvalidSessionException;
    public void stop() throws InvalidSessionException;
    public Collection<Object> getAttributeKeys() throws InvalidSessionException;
    public Object getAttribute(Object key) throws InvalidSessionException;
    public void setAttribute(Object key, Object value) throws InvalidSessionException;
    public Object removeAttribute(Object key) throws InvalidSessionException;

    /**
     * Returns true if this session is stopped (either expired or explicitly stopped).
     * @return true if this session is stopped, false otherwise
     */
    public boolean isStoppedOrExpired();

    /**
     * Returns true if this session has expired, false otherwise.
     * @return true if this session has expired, false otherwise
     */
    public boolean isExpired();

    /**
     * Validates this session by checking if it has stopped or expired.
     * @throws InvalidSessionException if this session has stopped or expired
     */
    public void validate() throws InvalidSessionException;
}

/**
 * Interface for sessions that can validate themselves.
 */
public interface ValidatingSession extends Session {
    /**
     * Returns true if this session has stopped or expired, false otherwise.
     * @return true if this session has stopped or expired, false otherwise
     */
    boolean isValid();

    /**
     * Validates the session, typically by checking if it has expired or been stopped.
     * @throws InvalidSessionException if the session is invalid
     */
    void validate() throws InvalidSessionException;
}

Session Context and Keys

Context objects for session creation and lookup.

/**
 * A SessionContext is used by SessionManager implementations to transport session creation context data.
 */
public interface SessionContext extends Map<String, Object> {
    /**
     * Returns the originating host name or IP address (as a String) from where the Session will be created.
     * @return the originating host name or IP address (as a String) from where the Session will be created
     */
    String getHost();

    /**
     * Sets the originating host name or IP address from where the Session will be created.
     * @param host the originating host name or IP address from where the Session will be created
     */
    void setHost(String host);
}

/**
 * Default implementation of the SessionContext interface.
 */
public class DefaultSessionContext implements SessionContext {
    public DefaultSessionContext();

    /**
     * Constructor accepting a map of session context data.
     * @param map the map containing initial session context data
     */
    public DefaultSessionContext(Map<String, Object> map);

    public String getHost();
    public void setHost(String host);
}

/**
 * A SessionKey is just a marker interface that represents a key that can be used to retrieve a Session.
 */
public interface SessionKey {
    /**
     * Returns the session ID referenced by this SessionKey instance.
     * @return the session ID referenced by this SessionKey instance
     */
    Serializable getSessionId();
}

/**
 * Default implementation of the SessionKey interface.
 */
public class DefaultSessionKey implements SessionKey {
    public DefaultSessionKey();

    /**
     * Constructor accepting a session ID.
     * @param sessionId the session ID
     */
    public DefaultSessionKey(Serializable sessionId);

    public Serializable getSessionId();
    public void setSessionId(Serializable sessionId);
}

Session Factory

Factory for creating session instances.

/**
 * A SessionFactory creates Session instances based on contextual information.
 */
public interface SessionFactory {
    /**
     * Creates a new Session instance based on the specified contextual initialization data.
     * @param initData the initialization data to be used during Session creation
     * @return a new Session instance
     */
    Session createSession(SessionContext initData);
}

/**
 * SessionFactory implementation that creates SimpleSession instances.
 */
public class SimpleSessionFactory implements SessionFactory {
    public SimpleSessionFactory();

    public Session createSession(SessionContext initData);
}

Session DAO (Data Access Object)

Interface for persisting and managing session data.

/**
 * Data Access Object design pattern specification to enable Session access to an EIS (Enterprise Information System).
 */
public interface SessionDAO {
    /**
     * Inserts a new Session record into the underlying EIS.
     * @param session the Session object to create in the EIS
     * @return the EIS record primary key created for the new Session record
     */
    Serializable create(Session session);

    /**
     * Retrieves the session from the EIS uniquely identified by the specified sessionId.
     * @param sessionId the system-wide unique identifier of the Session object to retrieve from the EIS
     * @return the persisted session in the EIS identified by sessionId
     */
    Session readSession(Serializable sessionId) throws UnknownSessionException;

    /**
     * Updates (persists) data from a previously created Session instance in the underlying EIS.
     * @param session the Session to update
     * @throws UnknownSessionException if no existing EIS session record exists with the identifier of session.getId()
     */
    void update(Session session) throws UnknownSessionException;

    /**
     * Deletes the associated EIS record of the specified Session instance.
     * @param session the Session to delete
     */
    void delete(Session session);

    /**
     * Returns all sessions in the EIS that are considered active.
     * @return all sessions in the EIS that are considered active
     */
    Collection<Session> getActiveSessions();
}

/**
 * Simple memory-based implementation of the SessionDAO interface.
 */
public class MemorySessionDAO extends AbstractSessionDAO {
    public MemorySessionDAO();

    protected Serializable doCreate(Session session);
    protected Session doReadSession(Serializable sessionId);
    public void update(Session session) throws UnknownSessionException;
    public void delete(Session session);
    public Collection<Session> getActiveSessions();
}

/**
 * SessionDAO implementation that relies on an enterprise caching product as the EIS record store.
 */
public class EnterpriseCacheSessionDAO extends CachingSessionDAO {
    public EnterpriseCacheSessionDAO();

    /**
     * Sets the name of the cache used to store active sessions.
     * @param activeSessionsCacheName the name of the cache used to store active sessions
     */
    public void setActiveSessionsCacheName(String activeSessionsCacheName);

    /**
     * Returns the name of the cache used to store active sessions.
     * @return the name of the cache used to store active sessions
     */
    public String getActiveSessionsCacheName();

    protected Serializable doCreate(Session session);
    protected Session doReadSession(Serializable sessionId);
    protected void doUpdate(Session session);
    protected void doDelete(Session session);
}

/**
 * Abstract SessionDAO implementation that assumes session storage in a cache or similar key/value store.
 */
public abstract class CachingSessionDAO extends AbstractSessionDAO implements CacheManagerAware {
    public CachingSessionDAO();

    /**
     * Sets the CacheManager to use for session storage.
     * @param cacheManager the CacheManager to use for session storage
     */
    public void setCacheManager(CacheManager cacheManager);

    /**
     * Returns the CacheManager used for session storage.
     * @return the CacheManager used for session storage
     */
    public CacheManager getCacheManager();
}

Usage Example:

// Configure different session storage options

// 1. Memory-based storage (default)
MemorySessionDAO memoryDAO = new MemorySessionDAO();

// 2. Enterprise cache-based storage  
EnterpriseCacheSessionDAO cacheDAO = new EnterpriseCacheSessionDAO();
cacheDAO.setCacheManager(cacheManager);
cacheDAO.setActiveSessionsCacheName("shiro-activeSessionsCache");

// 3. Custom database storage
public class DatabaseSessionDAO extends AbstractSessionDAO {
    @Override
    protected Serializable doCreate(Session session) {
        // Save to database and return generated ID
        return saveToDatabase(session);
    }
    
    @Override
    protected Session doReadSession(Serializable sessionId) {
        // Load from database
        return loadFromDatabase(sessionId);
    }
    
    @Override
    public void update(Session session) throws UnknownSessionException {
        // Update in database
        updateInDatabase(session);
    }
    
    @Override
    public void delete(Session session) {
        // Delete from database
        deleteFromDatabase(session);
    }
    
    @Override
    public Collection<Session> getActiveSessions() {
        // Return all active sessions from database
        return getActiveSessionsFromDatabase();
    }
}

Session ID Generation

Interface and implementations for generating session identifiers.

/**
 * Interface for components that can generate session IDs.
 */
public interface SessionIdGenerator {
    /**
     * Generates a new ID for a new session based on the specified session creation context.
     * @param session the new session instance for which an ID will be generated and then assigned
     * @return the session ID to assign to the specified session instance
     */
    Serializable generateId(Session session);
}

/**
 * SessionIdGenerator that generates String values of Java UUIDs as session IDs.
 */
public class JavaUuidSessionIdGenerator implements SessionIdGenerator {
    public JavaUuidSessionIdGenerator();

    public Serializable generateId(Session session);
}

Session Listeners

Event listeners for session lifecycle events.

/**
 * Interface to be implemented by components that wish to be notified of session lifecycle events.
 */
public interface SessionListener {
    /**
     * Notification callback that occurs when a new session has started.
     * @param session the session that has started
     */
    void onStart(Session session);

    /**
     * Notification callback that occurs when a session has been stopped, either programmatically or due to expiration.
     * @param session the session that has stopped
     */
    void onStop(Session session);

    /**
     * Notification callback that occurs when a session has expired.
     * @param session the session that has expired
     */
    void onExpiration(Session session);
}

/**
 * Simple adapter implementation of the SessionListener interface that provides empty method implementations.
 */
public class SessionListenerAdapter implements SessionListener {
    public void onStart(Session session) {}
    public void onStop(Session session) {}
    public void onExpiration(Session session) {}
}

Usage Example:

// Create custom session listener
public class MySessionListener implements SessionListener {
    @Override
    public void onStart(Session session) {
        System.out.println("Session started: " + session.getId());
        // Log session start, initialize user activity tracking, etc.
    }
    
    @Override
    public void onStop(Session session) {
        System.out.println("Session stopped: " + session.getId());
        // Clean up user-specific resources, log session end, etc.
    }
    
    @Override
    public void onExpiration(Session session) {
        System.out.println("Session expired: " + session.getId());
        // Handle expired session cleanup
    }
}

// Configure session manager with listener
DefaultSessionManager sessionManager = new DefaultSessionManager();
sessionManager.getSessionListeners().add(new MySessionListener());

Exception Hierarchy

/**
 * Base exception for all Session-related problems.
 */
public class SessionException extends ShiroException {
    public SessionException();
    public SessionException(String message);
    public SessionException(Throwable cause);
    public SessionException(String message, Throwable cause);
}

/**
 * Exception thrown when attempting to interact with an invalid session.
 */
public class InvalidSessionException extends SessionException {
    public InvalidSessionException();
    public InvalidSessionException(String message);
    public InvalidSessionException(Throwable cause);
    public InvalidSessionException(String message, Throwable cause);
}

/**
 * Exception thrown when attempting to interact with a session that has been explicitly stopped.
 */
public class StoppedSessionException extends InvalidSessionException {
    public StoppedSessionException();
    public StoppedSessionException(String message);
    public StoppedSessionException(Throwable cause);
    public StoppedSessionException(String message, Throwable cause);
}

/**
 * Exception thrown when attempting to interact with a session that has expired.
 */
public class ExpiredSessionException extends StoppedSessionException {
    public ExpiredSessionException();
    public ExpiredSessionException(String message);
    public ExpiredSessionException(Throwable cause);
    public ExpiredSessionException(String message, Throwable cause);
}

/**
 * Exception thrown when referencing a session that cannot be found.
 */
public class UnknownSessionException extends InvalidSessionException {
    public UnknownSessionException();
    public UnknownSessionException(String message);
    public UnknownSessionException(Throwable cause);
    public UnknownSessionException(String message, Throwable cause);
}

Install with Tessl CLI

npx tessl i tessl/maven-org-apache-shiro--shiro-core

docs

authentication.md

authorization.md

index.md

realms.md

security-annotations.md

security-manager.md

session-management.md

subject-operations.md

utilities.md

tile.json