User session management

User sessions in TYPO3 are represented as UserSession objects. The TYPO3 authentication service chain creates or updates user sessions when authenticating users.

The UserSession object contains all information regarding a user's session, for website visitors with session data (e.g. basket for anonymous / not-logged-in users), for frontend users as well as authenticated backend users. These are for example, the session id, the session data, if a session was updated, if the session is anonymous, or if it is marked as permanent and so on.

The UserSession object can be used to change and retrieve information in an object-oriented way.

For creating UserSession objects the UserSessionManager must be used since this manager acts as the main factory for user sessions and therefore handles all necessary tasks like fetching, evaluating and persisting them. Effectively encapsulating all calls to the SessionManager which is used for the session backend.

Public API of UserSessionManager

The UserSessionManager can be retrieved using its static factory method create():

EXT:some_extension/Classes/Controller/SomeController.php
use TYPO3\CMS\Core\Session\UserSessionManager;

$loginType = 'BE'; // or 'FE' for frontend
$userSessionManager = UserSessionManager::create($loginType);
Copied!

You can then use the UserSessionManager to work with user sessions. A couple of public methods are available:

class UserSessionManager
Fully qualified name
\TYPO3\CMS\Core\Session\UserSessionManager

The purpose of the UserSessionManager is to create new user session objects (acting as a factory), depending on the need / request, and to fetch sessions from the session backend, effectively encapsulating all calls to the SessionManager.

The UserSessionManager can be retrieved using its static factory method create():

use TYPO3\CMS\Core\Session\UserSessionManager;

$loginType = 'BE'; // or 'FE' for frontend
$userSessionManager = UserSessionManager::create($loginType);
Copied!
createFromRequestOrAnonymous ( \Psr\Http\Message\ServerRequestInterface $request, string $cookieName)

Creates and returns a session from the given request. If the given $cookieName can not be obtained from the request an anonymous session will be returned.

param $request

the request

param $cookieName

Name of the cookie that might contain the session

Return description

An existing session if one is stored in the cookie, an anonymous session otherwise

Returns
\UserSession
createAnonymousSession ( )

Creates and returns an anonymous session object (which is not persisted)

Returns
\TYPO3\CMS\Core\Session\UserSession
hasExpired ( \TYPO3\CMS\Core\Session\UserSession $session)

Checks whether a session has expired. This is also the case if sessionLifetime is 0

param $session

the session

Returns
bool
willExpire ( \TYPO3\CMS\Core\Session\UserSession $session, int $gracePeriod)

Checks whether a given user session will expire within the given grace period

param $session

the session

param $gracePeriod

in seconds

Returns
bool
fixateAnonymousSession ( \TYPO3\CMS\Core\Session\UserSession $session, bool $isPermanent = false)

Persists an anonymous session without a user logged-in, in order to store session data between requests

param $session

The user session to fixate

param $isPermanent

If true, the session will get the ses_permanent flag, default: false

Return description

A new session object with an updated ses_tstamp (allowing to keep the session alive)

Returns
\UserSession
elevateToFixatedUserSession ( \TYPO3\CMS\Core\Session\UserSession $session, int $userId, bool $isPermanent = false)

Removes existing entries, creates and returns a new user session object.

See regenerateSession() below.

param $session

The user session to recreate

param $userId

The user id the session belongs to

param $isPermanent

If true, the session will get the ses_permanent flag, default: false

Return description

The newly created user session object

Returns
\UserSession
regenerateSession ( string $sessionId, array $existingSessionRecord = [], bool $anonymous = false)

Regenerates the given session. This method should be used whenever a user proceeds to a higher authorization level, for example when an anonymous session is now authenticated.

param $sessionId

The session id

param $existingSessionRecord

If given, this session record will be used instead of fetching again, default: []

param $anonymous

If true session will be regenerated as anonymous session, default: false

Returns
\TYPO3\CMS\Core\Session\UserSession
updateSessionTimestamp ( \TYPO3\CMS\Core\Session\UserSession $session)

Updates the session timestamp for the given user session if the session is marked as "needs update" (which means the current timestamp is greater than "last updated + a specified grace-time").

param $session

the session

Return description

A modified user session with a last updated value if needed

Returns
\UserSession
isSessionPersisted ( \TYPO3\CMS\Core\Session\UserSession $session)

Checks whether a given session is already persisted

param $session

the session

Returns
bool
removeSession ( \TYPO3\CMS\Core\Session\UserSession $session)

Removes a given session from the session backend

param $session

the session

updateSession ( \TYPO3\CMS\Core\Session\UserSession $session)

Updates the session data + timestamp in the session backend

param $session

the session

Returns
\TYPO3\CMS\Core\Session\UserSession
collectGarbage ( int $garbageCollectionProbability = 1)

Calls the session backends collectGarbage() method

param $garbageCollectionProbability

the garbageCollectionProbability, default: 1

create ( string $loginType, ?int $sessionLifetime = NULL, ?\TYPO3\CMS\Core\Session\SessionManager $sessionManager = NULL, ?\TYPO3\CMS\Core\Authentication\IpLocker $ipLocker = NULL)

Creates a UserSessionManager instance for the given login type. Has several optional arguments used for testing purposes to inject dummy objects if needed.

Ideally, this factory encapsulates all TYPO3_CONF_VARS options, so the actual object does not need to consider any global state.

param $loginType

the loginType

param $sessionLifetime

the sessionLifetime, default: NULL

param $sessionManager

the sessionManager, default: NULL

param $ipLocker

the ipLocker, default: NULL

Returns
static
setLogger ( \Psr\Log\LoggerInterface $logger)

Sets a logger.

param $logger

the logger

Public API of UserSession

Changed in version 12.4.8

The signature of the methods getJwt() and resolveIdentifierFromJwt() has changed. The methods now have an additional argument $scope.

The session object created or retrieved by the UserSessionManager provides the following API methods:

class UserSession
Fully qualified name
\TYPO3\CMS\Core\Session\UserSession

Represents all information about a user's session.

A user session can be bound to a frontend / backend user, or an anonymous session based on session data stored in the session backend.

If a session is anonymous, it can be fixated by storing the session in the backend, but only if there is data in the session.

if a session is user-bound, it is automatically fixated.

The $isNew flag is meant to show that this user session object was not fetched from the session backend, but initialized in the first place by the current request.

The $data argument stores arbitrary data valid for the user's session.

A permanent session is not issued by a session-based cookie but a time-based cookie. The session might be persisted in the user's browser.

getIdentifier ( )
Return description

The session ID. This is the ses_id respectively the AbstractUserAuthentication->id

Returns
string
getUserId ( )
Return description

The user ID the session belongs to. Can also return 0 or NULL Which indicates an anonymous session. This is the ses_userid.

Returns
?int
getLastUpdated ( )
Return description

The timestamp of the last session data update. This is the ses_tstamp.

Returns
int
set ( string $key, ?mixed $value)

Sets or updates session data value for a given $key. It is also internally used if calling AbstractUserAuthentication->setSessionData()

param $key

The key whose value should be updated

param $value

The value or NULL to unset the key

hasData ( )

Checks whether the session has data assigned

Returns
bool
get ( string $key)

Returns the session data for the given $key or NULL if the key does not exist. It is internally used if calling AbstractUserAuthentication->getSessionData()

param $key

the key

getData ( )
Return description

The whole data array.

Returns
array
overrideData ( array $data)

Overrides the whole data array. Can also be used to unset the array.

This also sets the $wasUpdated pointer to true

param $data

the data

dataWasUpdated ( )

Checks whether the session data has been updated

Returns
bool
isAnonymous ( )

Checks if the user session is an anonymous one. This means, the session does not belong to a logged-in user

Returns
bool
getIpLock ( )
Return description

The ipLock state of the session

Returns
string
isNew ( )

Checks whether the session is marked as new

Returns
bool
isPermanent ( )

Checks whether the session was marked as permanent

Returns
bool
needsUpdate ( )

Checks whether the session has to be updated

Returns
bool
getJwt ( ?\TYPO3\CMS\Core\Http\CookieScope $scope = NULL)

Gets session ID wrapped in JWT to be used for emitting a new cookie.

Cookie: <JWT(HS256, [identifier => <session-id>], <signature(encryption-key, cookie-domain)>)>

param $scope

the scope, default: NULL

Return description

The session ID wrapped in JWT to be used for emitting a new cookie

Returns
string
createFromRecord ( string $id, array $record, bool $markAsNew = false)

Creates a new user session based on the provided session record

param $id

the session identifier

param $record

the record

param $markAsNew

the markAsNew, default: false

Returns
self
createNonFixated ( string $identifier)

Creates a non fixated user session. This means the session does not belong to a logged-in user

param $identifier

the identifier

Returns
self
resolveIdentifierFromJwt ( string $cookieValue, \TYPO3\CMS\Core\Http\CookieScope $scope)

Verifies and resolves the session ID from a submitted cookie value: Cookie: <JWT(HS256, [identifier => <session-id>], <signature(encryption-key, cookie-domain)>)>

param $cookieValue

submitted cookie value

param $scope

the scope

Return description

Session ID, null in case verification failed

Returns
non-empty-string|null