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 \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 Psr\\Http\\Message\\ServerRequestInterface $request

the request

param string $cookieName

Name of the cookie that might contain the session

returntype

TYPO3\CMS\Core\Session\UserSession

Returns:

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

createAnonymousSession ( )

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

returntype

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 TYPO3\\CMS\\Core\\Session\\UserSession $session

the session

returntype

bool

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

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

param TYPO3\\CMS\\Core\\Session\\UserSession $session

the session

param int $gracePeriod

in seconds

returntype

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 TYPO3\\CMS\\Core\\Session\\UserSession $session

The user session to fixate

param bool $isPermanent

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

returntype

TYPO3\CMS\Core\Session\UserSession

Returns:

UserSession 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.

param TYPO3\\CMS\\Core\\Session\\UserSession $session

The user session to recreate

param int $userId

The user id the session belongs to

param bool $isPermanent

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

returntype

TYPO3\CMS\Core\Session\UserSession

Returns:

UserSession 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.

param string $sessionId

The session id

param array $existingSessionRecord

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

param bool $anonymous

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

returntype

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 TYPO3\\CMS\\Core\\Session\\UserSession $session

the session

returntype

TYPO3\CMS\Core\Session\UserSession

Returns:

UserSession 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

param TYPO3\\CMS\\Core\\Session\\UserSession $session

the session

returntype

bool

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

Removes a given session from the session backend

param TYPO3\\CMS\\Core\\Session\\UserSession $session

the session

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

Updates the session data + timestamp in the session backend

param TYPO3\\CMS\\Core\\Session\\UserSession $session

the session

returntype

TYPO3\CMS\Core\Session\UserSession

collectGarbage ( int $garbageCollectionProbability = 1)

Calls the session backends collectGarbage() method

param int $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 string $loginType

the loginType

param int $sessionLifetime

the sessionLifetime, default: NULL

param TYPO3\\CMS\\Core\\Session\\SessionManager $sessionManager

the sessionManager, default: NULL

param TYPO3\\CMS\\Core\\Authentication\\IpLocker $ipLocker

the ipLocker, default: NULL

returntype

self

Returns:

static

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

Sets a logger.

param Psr\\Log\\LoggerInterface $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 \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 ( )
returntype

string

Returns:

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

getUserId ( )
returntype

int

Returns:

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

getLastUpdated ( )
returntype

int

Returns:

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

param string $key

The key whose value should be updated

param mixed $value

The value or NULL to unset the key

hasData ( )

Checks whether the session has data assigned

returntype

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 string $key

the key

getData ( )
returntype

array

Returns:

array 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

param array $data

the data

dataWasUpdated ( )

Checks whether the session data has been updated

returntype

bool

isAnonymous ( )

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

returntype

bool

getIpLock ( )
returntype

string

Returns:

string the ipLock state of the session

isNew ( )

Checks whether the session is marked as new

returntype

bool

isPermanent ( )

Checks whether the session was marked as permanent

returntype

bool

needsUpdate ( )

Checks whether the session has to be updated

returntype

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 TYPO3\\CMS\\Core\\Http\\CookieScope $scope

the scope, default: NULL

returntype

string

Returns:

string 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

param string $id

the session identifier

param array $record

the record

param bool $markAsNew

the markAsNew, default: false

returntype

self

createNonFixated ( string $identifier)

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

param string $identifier

the identifier

returntype

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 string $cookieValue

submitted cookie value

param TYPO3\\CMS\\Core\\Http\\CookieScope $scope

the scope

returntype

string

Returns:

non-empty-string|null session ID, null in case verification failed