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);

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

class 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);
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.

Parameters
  • $request (Psr\Http\Message\ServerRequestInterface) -- the request

  • $cookieName (string) -- Name of the cookie that might contain the session

Return type

TYPO3\CMS\Core\Session\UserSession

Returns

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

createFromGlobalCookieOrAnonymous(string $cookieName)

Deprecated: use createFromRequestOrAnonymous() instead. Will be removed in TYPO3 v13.0.

Creates and returns a session from a global cookie ($_COOKIE). If no cookie can be found for the given name, an anonymous session will be returned. It is recommended to use the PSR-7-Request based method instead.

Parameters
  • $cookieName (string) -- the cookieName

Return type

TYPO3\CMS\Core\Session\UserSession

createAnonymousSession()

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

Return type

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

Parameters
Return type

bool

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

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

Parameters
Return type

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

Parameters
Return type

TYPO3\CMS\Core\Session\UserSession

Returns

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

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.

Parameters
  • $session (TYPO3\CMS\Core\Session\UserSession) -- The user session to recreate

  • $userId (int) -- The user id the session belongs to

  • $isPermanent (bool) -- If true, the session will get the ses_permanent flag, default: false

Return type

TYPO3\CMS\Core\Session\UserSession

Returns

The newly created user session object

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.

Parameters
  • $sessionId (string) -- The session id

  • $existingSessionRecord (array) -- If given, this session record will be used instead of fetching again, default: []

  • $anonymous (bool) -- If true session will be regenerated as anonymous session, default: false

Return type

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").

Parameters
Return type

TYPO3\CMS\Core\Session\UserSession

Returns

a modified user session with a last updated value if needed

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

Checks whether a given session is already persisted

Parameters
Return type

bool

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

Removes a given session from the session backend

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

Updates the session data + timestamp in the session backend

Parameters
Return type

TYPO3\CMS\Core\Session\UserSession

collectGarbage(int $garbageCollectionProbability = 1)

Calls the session backends collectGarbage() method

Parameters
  • $garbageCollectionProbability (int) -- 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.

Parameters
  • $loginType (string) -- the loginType

  • $sessionLifetime (int) -- the sessionLifetime, default: NULL

  • $sessionManager (TYPO3\CMS\Core\Session\SessionManager) -- the sessionManager, default: NULL

  • $ipLocker (TYPO3\CMS\Core\Authentication\IpLocker) -- the ipLocker, default: NULL

Return type

self

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

Sets a logger.

Parameters
  • $logger (Psr\Log\LoggerInterface) -- the logger

Public API of UserSession

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

class 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 type

string

Returns

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

getUserId()
Return type

int

Returns

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

getLastUpdated()
Return type

int

Returns

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

set(string $key, mixed $value)

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

Parameters
  • $key (string) -- The key whose value should be updated

  • $value (mixed) -- The value or NULL to unset the key

hasData()

Checks whether the session has data assigned

Return type

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()

Parameters
  • $key (string) -- the key

getData()
Return type

array

Returns

the whole data 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

Parameters
  • $data (array) -- the data

dataWasUpdated()

Checks whether the session data has been updated

Return type

bool

isAnonymous()

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

Return type

bool

getIpLock()
Return type

string

Returns

the ipLock state of the session

isNew()

Checks whether the session is marked as new

Return type

bool

isPermanent()

Checks whether the session was marked as permanent

Return type

bool

needsUpdate()

Checks whether the session has to be updated

Return type

bool

getJwt()

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

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

Return type

string

Returns

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

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

Creates a new user session based on the provided session record

Parameters
  • $id (string) -- the session identifier

  • $record (array) -- the record

  • $markAsNew (bool) -- the markAsNew, default: false

Return type

self

createNonFixated(string $identifier)

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

Parameters
  • $identifier (string) -- the identifier

Return type

self

resolveIdentifierFromJwt(string $cookieValue)

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

Parameters
  • $cookieValue (string) -- submitted cookie value

Return type

string

Returns

session ID, null in case verification failed