Skip to content
PHP Ecosystem
Explore

User

API reference › yii › web › User

classyii\web\User
Extendsyii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/web/User.php

User is the class for the user application component that manages the user authentication status.

You may use $isGuest to determine whether the current user is a guest or not. If the user is a guest, the $identity property would return null. Otherwise, it would be an instance of IdentityInterface.

You may call various methods to change the user authentication status:

  • login(): sets the specified identity and remembers the authentication status in session and cookie;
  • logout(): marks the user as a guest and clears the relevant information from session and cookie;
  • setIdentity(): changes the user identity without touching session or cookie (this is best used in stateless RESTful API implementation).

Note that User only maintains the user authentication status. It does NOT handle how to authenticate a user. The logic of how to authenticate a user should be done in the class implementing IdentityInterface. You are also required to set $identityClass with the name of this class.

User is configured as an application component in Application by default. You can access that instance via Yii::$app->user.

You can modify its configuration by adding an array to your application config under components as it is shown in the following example:

'user' => [
'identityClass' => 'app\models\User', // User must implement the IdentityInterface
'enableAutoLogin' => true,
// 'loginUrl' => ['user/login'],
// ...
]
PropertyTypeDescriptionDefined by
$absoluteAuthTimeoutint|nullThe number of seconds in which the user will be logged out automatically regardless of activity. Default: null.User
$absoluteAuthTimeoutParamstringThe session variable name used to store the value of absolute expiration timestamp of the authenticated state. Default: '__absoluteExpire'.User
$acceptableRedirectTypesarrayMIME types for which this component should redirect to the $loginUrl. Default: ['text/html', 'application/xhtml+xml']. Available since 2.0.8.User
$accessCheckeryii\rbac\CheckAccessInterface|string|array|nullThe access checker object to use for checking access or the application component ID of the access checker. Default: null. Available since 2.0.9.User
$authKeyParamstringThe session variable name used to store authentication key. Default: '__authKey'. Available since 2.0.41.User
$authTimeoutint|nullThe number of seconds in which the user will be logged out automatically if the user remains inactive. Default: null.User
$authTimeoutParamstringThe session variable name used to store the value of expiration timestamp of the authenticated state. Default: '__expire'.User
$autoRenewCookieboolWhether to automatically renew the identity cookie each time a page is requested. Default: true.User
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$enableAutoLoginboolWhether to enable cookie-based login. Default: false.User
$enableSessionboolWhether to use session to persist authentication status across multiple requests. Default: true.User
$id read-onlystring|int|nullThe unique identifier for the user.User
$identityyii\web\T|nullThe identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated).User
$identityClassclass-string<yii\web\T>The class name of the $identity object. Default: null.User
$identityCookiearrayThe configuration of the identity cookie. Default: ['name' => '_identity', 'httpOnly' => true].User
$idParamstringThe session variable name used to store the value of $id. Default: '__id'.User
$isGuest read-onlyboolWhether the current user is a guest.User
$loginUrlstring|array|nullThe URL for login when loginRequired() is called. Default: ['site/login'].User
$returnUrlstring|arrayThe URL that the user should be redirected to after login.User
$returnUrlParamstringThe session variable name used to store the value of $returnUrl. Default: '__returnUrl'.User
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
can()Checks if the user can perform the operation as specified by the given permission.User
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
checkRedirectAcceptable()Checks if the Accept header contains a content type that allows redirection to the login page.User
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getId()Returns a value that uniquely represents the user.User
getIdentity()Returns the identity object associated with the currently logged-in user.User
getIsGuest()Returns a value indicating whether the user is a guest (not authenticated).User
getReturnUrl()Returns the URL that the browser should be redirected to after successful login.User
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the application component.User
login()Logs in a user.User
loginByAccessToken()Logs in a user by the given access token.User
loginRequired()Redirects the user browser to the login page.User
logout()Logs out the current user.User
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
setIdentity()Sets the user identity object.User
setReturnUrl()Remembers the URL in the session so that it can be retrieved back later by getReturnUrl().User
switchIdentity()Switches to a new identity for the current user.User
trigger()Triggers an event.yii\base\Component
afterLogin() protectedThis method is called after the user is successfully logged in.User
afterLogout() protectedThis method is invoked right after a user is logged out via logout().User
beforeLogin() protectedThis method is called before logging in a user.User
beforeLogout() protectedThis method is invoked when calling logout() to log out a user.User
getAccessChecker() protectedReturns the access checker used for checking access.User
getIdentityAndDurationFromCookie() protectedDetermines if an identity cookie has a valid format and contains a valid auth key.User
loginByCookie() protectedLogs in a user by cookie.User
regenerateCsrfToken() protectedRegenerates CSRF tokenUser
removeIdentityCookie() protectedRemoves the identity cookie.User
renewAuthStatus() protectedUpdates the authentication status using the information from session and cookie.User
renewIdentityCookie() protectedRenews the identity cookie.User
sendIdentityCookie() protectedSends an identity cookie.User
ConstantValueDescriptionDefined by
EVENT_BEFORE_LOGIN'beforeLogin'User
EVENT_AFTER_LOGIN'afterLogin'User
EVENT_BEFORE_LOGOUT'beforeLogout'User
EVENT_AFTER_LOGOUT'afterLogout'User
public int|null $absoluteAuthTimeout = null

The number of seconds in which the user will be logged out automatically regardless of activity.

Note that this will not work if $enableAutoLogin is true.

public string $absoluteAuthTimeoutParam = '__absoluteExpire'

The session variable name used to store the value of absolute expiration timestamp of the authenticated state.

This is used when $absoluteAuthTimeout is set.

public yii\rbac\CheckAccessInterface|string|array|null $accessChecker = null

The access checker object to use for checking access or the application component ID of the access checker.

If not set the application auth manager will be used.

Since

2.0.9

public int|null $authTimeout = null

The number of seconds in which the user will be logged out automatically if the user remains inactive.

If this property is not set, the user will be logged out after the current session expires (c.f. Session::$timeout). Note that this will not work if $enableAutoLogin is true.

public string $authTimeoutParam = '__expire'

The session variable name used to store the value of expiration timestamp of the authenticated state.

This is used when $authTimeout is set.

public bool $autoRenewCookie = true

Whether to automatically renew the identity cookie each time a page is requested.

This property is effective only when $enableAutoLogin is true. When this is false, the identity cookie will expire after the specified duration since the user is initially logged in. When this is true, the identity cookie will expire after the specified duration since the user visits the site the last time.

public bool $enableAutoLogin = false

Whether to enable cookie-based login.

Defaults to false. Note that this property will be ignored if $enableSession is false.

public bool $enableSession = true

Whether to use session to persist authentication status across multiple requests.

You set this property to be false if your application is stateless, which is often the case for RESTful APIs.

public string|int|null $id

The unique identifier for the user.

If null, it means the user is a guest.

Access

Read-only (virtual property).

public array $identityCookie = ['name' => '_identity', 'httpOnly' => true]

The configuration of the identity cookie.

This property is used only when $enableAutoLogin is true.

public string|array|null $loginUrl = ['site/login']

The URL for login when loginRequired() is called.

If an array is given, UrlManager::createUrl() will be called to create the corresponding URL. The first element of the array should be the route to the login action, and the rest of the name-value pairs are GET parameters used to construct the login URL. For example,

['site/login', 'ref' => 1]

If this property is null, a 403 HTTP exception will be raised when loginRequired() is called.

public string|array $returnUrl

The URL that the user should be redirected to after login.

If an array is given, UrlManager::createUrl() will be called to create the corresponding URL. The first element of the array should be the route, and the rest of the name-value pairs are GET parameters used to construct the URL. For example,

['admin/index', 'ref' => 1]
public function can(string $permissionName, array $params = [], bool $allowCaching = true): bool

Checks if the user can perform the operation as specified by the given permission.

Note that you must configure “authManager” application component in order to use this method. Otherwise it will always return false.

Parameters

ParameterTypeDescription
$permissionNamestringThe name of the permission (e.g. “edit post”) that needs access check.
$paramsarrayName-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user.
$allowCachingboolWhether to allow caching the result of access check. When this parameter is true (default), if the access check of an operation was performed before, its result will be directly returned when calling this method to check the same operation. If this parameter is false, this method will always call CheckAccessInterface::checkAccess() to obtain the up-to-date access result. Note that this caching is effective only within the same request and only works when $params = [].

Returns

bool: Whether the user can perform the operation as specified by the given permission.

public function checkRedirectAcceptable(): bool

Checks if the Accept header contains a content type that allows redirection to the login page.

The login page is assumed to serve text/html or application/xhtml+xml by default. You can change acceptable content types by modifying $acceptableRedirectTypes property.

Returns

bool: Whether this request may be redirected to the login page.

Since

2.0.8

See also

public function getId(): string|int|null

Returns a value that uniquely represents the user.

Returns

string|int|null: The unique identifier for the user. If null, it means the user is a guest.

See also

public function getIdentity(bool $autoRenew = true): yii\web\T|null

Returns the identity object associated with the currently logged-in user.

When $enableSession is true, this method may attempt to read the user’s authentication data stored in session and reconstruct the corresponding identity object, if it has not done so before.

Parameters

ParameterTypeDescription
$autoRenewboolWhether to automatically renew authentication status if it has not been done so before. This is only useful when $enableSession is true.

Returns

yii\web\T|null: The identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated).

See also

public function getIsGuest(): bool

Returns a value indicating whether the user is a guest (not authenticated).

Returns

bool: Whether the current user is a guest.

See also

public function getReturnUrl(string|array|null $defaultUrl = null): string

Returns the URL that the browser should be redirected to after successful login.

This method reads the return URL from the session. It is usually used by the login action which may call this method to redirect the browser to where it goes after successful authentication.

Parameters

ParameterTypeDescription
$defaultUrlstring|array|nullThe default return URL in case it was not set previously. If this is null and the return URL was not set previously, Application::$homeUrl will be redirected to. Please refer to setReturnUrl() on accepted format of the URL.

Returns

string: The URL that the user should be redirected to after login.

See also

public function init(): mixed

Initializes the application component.

Returns

mixed

public function login(yii\web\T $identity, int $duration = 0): bool

Logs in a user.

After logging in a user:

  • the user’s identity information is obtainable from the $identity property

If $enableSession is true:

  • the identity information will be stored in session and be available in the next requests
  • in case of $duration == 0: as long as the session remains active or till the user closes the browser
  • in case of $duration > 0: as long as the session remains active or as long as the cookie remains valid by it’s $duration in seconds when $enableAutoLogin is set true.

If $enableSession is false:

  • the $duration parameter will be ignored

Parameters

ParameterTypeDescription
$identityyii\web\TThe user identity (which should already be authenticated)
$durationintNumber of seconds that the user can remain in logged-in status, defaults to 0

Returns

bool: Whether the user is logged in

public function loginByAccessToken(string $token, mixed $type = null): yii\web\T|null

Logs in a user by the given access token.

This method will first authenticate the user by calling IdentityInterface::findIdentityByAccessToken() with the provided access token. If successful, it will call login() to log in the authenticated user. If authentication fails or login() is unsuccessful, it will return null.

Parameters

ParameterTypeDescription
$tokenstringThe access token
$typemixedThe type of the token. The value of this parameter depends on the implementation. For example, HttpBearerAuth will set this parameter to be yii\filters\auth\HttpBearerAuth.

Returns

yii\web\T|null: The identity associated with the given access token. Null is returned if the access token is invalid or login() is unsuccessful.

public function loginRequired(bool $checkAjax = true, bool $checkAcceptHeader = true): yii\web\Response

Redirects the user browser to the login page.

Before the redirection, the current URL (if it’s not an AJAX url) will be kept as $returnUrl so that the user browser may be redirected back to the current page after successful login.

Make sure you set $loginUrl so that the user browser can be redirected to the specified login URL after calling this method.

Note that when $loginUrl is set, calling this method will NOT terminate the application execution.

Parameters

ParameterTypeDescription
$checkAjaxboolWhether to check if the request is an AJAX request. When this is true and the request is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
$checkAcceptHeaderboolWhether to check if the request accepts HTML responses. Defaults to true. When this is true and the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.

Returns

Response: The redirection response if $loginUrl is set

Throws

public function logout(bool $destroySession = true): bool

Logs out the current user.

This will remove authentication-related session data. If $destroySession is true, all session data will be removed.

Parameters

ParameterTypeDescription
$destroySessionboolWhether to destroy the whole session. Defaults to true. This parameter is ignored if $enableSession is false.

Returns

bool: Whether the user is logged out

public function setIdentity(yii\web\T|null $identity): mixed

Sets the user identity object.

Note that this method does not deal with session or cookie. You should usually use switchIdentity() to change the identity of the current user.

Parameters

ParameterTypeDescription
$identityyii\web\T|nullThe identity object associated with the currently logged user. If null, it means the current user will be a guest without any associated identity.

Returns

mixed

Throws

public function setReturnUrl(string|array $url): mixed

Remembers the URL in the session so that it can be retrieved back later by getReturnUrl().

Parameters

ParameterTypeDescription
$urlstring|arrayThe URL that the user should be redirected to after login. If an array is given, UrlManager::createUrl() will be called to create the corresponding URL. The first element of the array should be the route, and the rest of the name-value pairs are GET parameters used to construct the URL. For example, [‘admin/index’, ‘ref’ => 1]

Returns

mixed

public function switchIdentity(yii\web\T|null $identity, int $duration = 0): mixed

Switches to a new identity for the current user.

When $enableSession is true, this method may use session and/or cookie to store the user identity information, according to the value of $duration. Please refer to login() for more details.

This method is mainly called by login(), logout() and loginByCookie() when the current user needs to be associated with the corresponding identity information.

Parameters

ParameterTypeDescription
$identityyii\web\T|nullThe identity information to be associated with the current user. If null, it means switching the current user to be a guest.
$durationintNumber of seconds that the user can remain in logged-in status. This parameter is used only when $identity is not null.

Returns

mixed

protected function afterLogin(yii\web\T $identity, bool $cookieBased, int $duration): mixed

This method is called after the user is successfully logged in.

The default implementation will trigger the EVENT_AFTER_LOGIN event. If you override this method, make sure you call the parent implementation so that the event is triggered.

Parameters

ParameterTypeDescription
$identityyii\web\TThe user identity information
$cookieBasedboolWhether the login is cookie-based
$durationintNumber of seconds that the user can remain in logged-in status. If 0, it means login till the user closes the browser or the session is manually destroyed.

Returns

mixed

protected function afterLogout(yii\web\T $identity): mixed

This method is invoked right after a user is logged out via logout().

The default implementation will trigger the EVENT_AFTER_LOGOUT event. If you override this method, make sure you call the parent implementation so that the event is triggered.

Parameters

ParameterTypeDescription
$identityyii\web\TThe user identity information

Returns

mixed

protected function beforeLogin(yii\web\T $identity, bool $cookieBased, int $duration): bool

This method is called before logging in a user.

The default implementation will trigger the EVENT_BEFORE_LOGIN event. If you override this method, make sure you call the parent implementation so that the event is triggered.

Parameters

ParameterTypeDescription
$identityyii\web\TThe user identity information
$cookieBasedboolWhether the login is cookie-based
$durationintNumber of seconds that the user can remain in logged-in status. If 0, it means login till the user closes the browser or the session is manually destroyed.

Returns

bool: Whether the user should continue to be logged in

protected function beforeLogout(yii\web\T $identity): bool

This method is invoked when calling logout() to log out a user.

The default implementation will trigger the EVENT_BEFORE_LOGOUT event. If you override this method, make sure you call the parent implementation so that the event is triggered.

Parameters

ParameterTypeDescription
$identityyii\web\TThe user identity information

Returns

bool: Whether the user should continue to be logged out

protected function getAccessChecker(): yii\rbac\CheckAccessInterface|null

Returns the access checker used for checking access.

Returns

yii\rbac\CheckAccessInterface|null

Since

2.0.9

protected function getIdentityAndDurationFromCookie(): array|null

Determines if an identity cookie has a valid format and contains a valid auth key.

This method is used when $enableAutoLogin is true. This method attempts to authenticate a user using the information in the identity cookie.

Returns

array|null: Returns an array of ‘identity’ and ‘duration’ if valid, otherwise null.

Since

2.0.9

See also

protected function loginByCookie(): mixed

Logs in a user by cookie.

This method attempts to log in a user using the ID and authKey information provided by the identity cookie.

Returns

mixed

protected function regenerateCsrfToken(): mixed

Regenerates CSRF token

Returns

mixed

Since

2.0.14.2

protected function removeIdentityCookie(): mixed

Removes the identity cookie.

This method is used when $enableAutoLogin is true.

Returns

mixed

Since

2.0.9

protected function renewAuthStatus(): mixed

Updates the authentication status using the information from session and cookie.

This method will try to determine the user identity using the $idParam session variable.

If $authTimeout is set, this method will refresh the timer.

If the user identity cannot be determined by session, this method will try to login by cookie if $enableAutoLogin is true.

Returns

mixed

protected function renewIdentityCookie(): mixed

Renews the identity cookie.

This method will set the expiration time of the identity cookie to be the current time plus the originally specified cookie duration.

Returns

mixed

protected function sendIdentityCookie(yii\web\T $identity, int $duration): mixed

Sends an identity cookie.

This method is used when $enableAutoLogin is true. It saves $id, auth key, and the duration of cookie-based login information in the cookie.

Parameters

ParameterTypeDescription
$identityyii\web\T
$durationintNumber of seconds that the user can remain in logged-in status.

Returns

mixed

See also