User
API reference › yii › web › User
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'], // ...]Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$absoluteAuthTimeout | int| | The number of seconds in which the user will be logged out automatically regardless of activity. Default: null. | User |
$absoluteAuthTimeoutParam | string | The session variable name used to store the value of absolute expiration timestamp of the authenticated state. Default: '__absoluteExpire'. | User |
$acceptableRedirectTypes | array | MIME types for which this component should redirect to the $loginUrl. Default: ['text/html',. Available since 2.0.8. | User |
$accessChecker | yii\| | The 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 |
$authKeyParam | string | The session variable name used to store authentication key. Default: '__authKey'. Available since 2.0.41. | User |
$authTimeout | int| | The number of seconds in which the user will be logged out automatically if the user remains inactive. Default: null. | User |
$authTimeoutParam | string | The session variable name used to store the value of expiration timestamp of the authenticated state. Default: '__expire'. | User |
$autoRenewCookie | bool | Whether to automatically renew the identity cookie each time a page is requested. Default: true. | User |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$enableAutoLogin | bool | Whether to enable cookie-based login. Default: false. | User |
$enableSession | bool | Whether to use session to persist authentication status across multiple requests. Default: true. | User |
$id read-only | string| | The unique identifier for the user. | User |
$identity | yii\ | The identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated). | User |
$identityClass | class-string<yii\ | The class name of the $identity object. Default: null. | User |
$identityCookie | array | The configuration of the identity cookie. Default: ['name' => '_identity',. | User |
$idParam | string | The session variable name used to store the value of $id. Default: '__id'. | User |
$isGuest read-only | bool | Whether the current user is a guest. | User |
$loginUrl | string| | The URL for login when loginRequired() is called. Default: ['site/login']. | User |
$returnUrl | string| | The URL that the user should be redirected to after login. | User |
$returnUrlParam | string | The session variable name used to store the value of $returnUrl. Default: '__returnUrl'. | User |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
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\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
checkRedirectAcceptable() | Checks if the Accept header contains a content type that allows redirection to the login page. | User |
className() static | Returns the fully qualified name of this class. | yii\ |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
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\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
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\ |
on() | Attaches an event handler to an event. | yii\ |
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\ |
afterLogin() protected | This method is called after the user is successfully logged in. | User |
afterLogout() protected | This method is invoked right after a user is logged out via logout(). | User |
beforeLogin() protected | This method is called before logging in a user. | User |
beforeLogout() protected | This method is invoked when calling logout() to log out a user. | User |
getAccessChecker() protected | Returns the access checker used for checking access. | User |
getIdentityAndDurationFromCookie() protected | Determines if an identity cookie has a valid format and contains a valid auth key. | User |
loginByCookie() protected | Logs in a user by cookie. | User |
regenerateCsrfToken() protected | Regenerates CSRF token | User |
removeIdentityCookie() protected | Removes the identity cookie. | User |
renewAuthStatus() protected | Updates the authentication status using the information from session and cookie. | User |
renewIdentityCookie() protected | Renews the identity cookie. | User |
sendIdentityCookie() protected | Sends an identity cookie. | User |
Constants
Section titled “Constants”| Constant | Value | Description | Defined by |
|---|---|---|---|
EVENT_BEFORE_LOGIN | 'beforeLogin' | User | |
EVENT_AFTER_LOGIN | 'afterLogin' | User | |
EVENT_BEFORE_LOGOUT | 'beforeLogout' | User | |
EVENT_AFTER_LOGOUT | 'afterLogout' | User |
Property details
Section titled “Property details”$absoluteAuthTimeout
Section titled “$absoluteAuthTimeout ”public int|null $absoluteAuthTimeout = nullThe 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.
$absoluteAuthTimeoutParam
Section titled “$absoluteAuthTimeoutParam ”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.
$accessChecker
Section titled “$accessChecker ”public yii\rbac\CheckAccessInterface|string|array|null $accessChecker = nullThe 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
$authTimeout
Section titled “$authTimeout ”public int|null $authTimeout = nullThe 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.
$authTimeoutParam
Section titled “$authTimeoutParam ”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.
$autoRenewCookie
Section titled “$autoRenewCookie ”public bool $autoRenewCookie = trueWhether 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.
$enableAutoLogin
Section titled “$enableAutoLogin ”public bool $enableAutoLogin = falseWhether to enable cookie-based login.
Defaults to false.
Note that this property will be ignored if $enableSession is false.
$enableSession
Section titled “$enableSession ”public bool $enableSession = trueWhether 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 $idThe unique identifier for the user.
If null, it means the user is a
guest.
Access
Read-only (virtual property).
$identityCookie
Section titled “$identityCookie ”public array $identityCookie = ['name' => '_identity', 'httpOnly' => true]The configuration of the identity cookie.
This property is used only when $enableAutoLogin is true.
$loginUrl
Section titled “$loginUrl ”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.
$returnUrl
Section titled “$returnUrl ”public string|array $returnUrlThe 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]Method details
Section titled “Method details”can()
Section titled “can() ”public function can(string $permissionName, array $params = [], bool $allowCaching = true): boolChecks 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
| Parameter | Type | Description |
|---|---|---|
$permissionName | string | The name of the permission (e.g. “edit post”) that needs access check. |
$params | array | Name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user. |
$allowCaching | bool | Whether 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.
checkRedirectAcceptable()
Section titled “checkRedirectAcceptable() ”public function checkRedirectAcceptable(): boolChecks 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
getId()
Section titled “getId() ”public function getId(): string|int|nullReturns 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
getIdentity()
Section titled “getIdentity() ”public function getIdentity(bool $autoRenew = true): yii\web\T|nullReturns 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
| Parameter | Type | Description |
|---|---|---|
$autoRenew | bool | Whether 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
getIsGuest()
Section titled “getIsGuest() ”public function getIsGuest(): boolReturns a value indicating whether the user is a guest (not authenticated).
getReturnUrl()
Section titled “getReturnUrl() ”public function getReturnUrl(string|array|null $defaultUrl = null): stringReturns 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
| Parameter | Type | Description |
|---|---|---|
$defaultUrl | string| | The 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
init()
Section titled “init() ”public function init(): mixedInitializes the application component.
Returns
mixed
login()
Section titled “login() ”public function login(yii\web\T $identity, int $duration = 0): boolLogs in a user.
After logging in a user:
- the user’s identity information is obtainable from the
$identityproperty
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$durationin seconds when$enableAutoLoginis settrue.
If $enableSession is false:
- the
$durationparameter will be ignored
Parameters
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | The user identity (which should already be authenticated) |
$duration | int | Number of seconds that the user can remain in logged-in status, defaults to 0 |
Returns
bool: Whether the user is logged in
loginByAccessToken()
Section titled “loginByAccessToken() ”public function loginByAccessToken(string $token, mixed $type = null): yii\web\T|nullLogs 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
| Parameter | Type | Description |
|---|---|---|
$token | string | The access token |
$type | mixed | The type of the token. The value of this parameter depends on the implementation. For example, HttpBearerAuth will set this parameter to be yii\. |
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.
loginRequired()
Section titled “loginRequired() ”public function loginRequired(bool $checkAjax = true, bool $checkAcceptHeader = true): yii\web\ResponseRedirects 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
| Parameter | Type | Description |
|---|---|---|
$checkAjax | bool | Whether 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. |
$checkAcceptHeader | bool | Whether 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
ForbiddenHttpException: the “Access Denied” HTTP exception if$loginUrlis not set or a redirect is not applicable.
logout()
Section titled “logout() ”public function logout(bool $destroySession = true): boolLogs out the current user.
This will remove authentication-related session data.
If $destroySession is true, all session data will be removed.
Parameters
| Parameter | Type | Description |
|---|---|---|
$destroySession | bool | Whether to destroy the whole session. Defaults to true. This parameter is ignored if $enableSession is false. |
Returns
bool: Whether the user is logged out
setIdentity()
Section titled “setIdentity() ”public function setIdentity(yii\web\T|null $identity): mixedSets 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
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | The 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
yii\base\InvalidValueException: if$identityobject does not implementIdentityInterface.
setReturnUrl()
Section titled “setReturnUrl() ”public function setReturnUrl(string|array $url): mixedRemembers the URL in the session so that it can be retrieved back later by getReturnUrl().
Parameters
| Parameter | Type | Description |
|---|---|---|
$url | string| | 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] |
Returns
mixed
switchIdentity()
Section titled “switchIdentity() ”public function switchIdentity(yii\web\T|null $identity, int $duration = 0): mixedSwitches 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
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | The identity information to be associated with the current user. If null, it means switching the current user to be a guest. |
$duration | int | Number of seconds that the user can remain in logged-in status. This parameter is used only when $identity is not null. |
Returns
mixed
afterLogin()
Section titled “afterLogin() ”protected function afterLogin(yii\web\T $identity, bool $cookieBased, int $duration): mixedThis 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
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | The user identity information |
$cookieBased | bool | Whether the login is cookie-based |
$duration | int | Number 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
afterLogout()
Section titled “afterLogout() ”protected function afterLogout(yii\web\T $identity): mixedThis 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
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | The user identity information |
Returns
mixed
beforeLogin()
Section titled “beforeLogin() ”protected function beforeLogin(yii\web\T $identity, bool $cookieBased, int $duration): boolThis 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
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | The user identity information |
$cookieBased | bool | Whether the login is cookie-based |
$duration | int | Number 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
beforeLogout()
Section titled “beforeLogout() ”protected function beforeLogout(yii\web\T $identity): boolThis 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
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | The user identity information |
Returns
bool: Whether the user should continue to be logged out
getAccessChecker()
Section titled “getAccessChecker() ”protected function getAccessChecker(): yii\rbac\CheckAccessInterface|nullReturns the access checker used for checking access.
getIdentityAndDurationFromCookie()
Section titled “getIdentityAndDurationFromCookie() ”protected function getIdentityAndDurationFromCookie(): array|nullDetermines 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
loginByCookie()
Section titled “loginByCookie() ”protected function loginByCookie(): mixedLogs 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
regenerateCsrfToken()
Section titled “regenerateCsrfToken() ”protected function regenerateCsrfToken(): mixedRegenerates CSRF token
Returns
mixed
Since
2.0.14.2
removeIdentityCookie()
Section titled “removeIdentityCookie() ”protected function removeIdentityCookie(): mixedRemoves the identity cookie.
This method is used when $enableAutoLogin is true.
Returns
mixed
Since
2.0.9
renewAuthStatus()
Section titled “renewAuthStatus() ”protected function renewAuthStatus(): mixedUpdates 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
renewIdentityCookie()
Section titled “renewIdentityCookie() ”protected function renewIdentityCookie(): mixedRenews 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
sendIdentityCookie()
Section titled “sendIdentityCookie() ”protected function sendIdentityCookie(yii\web\T $identity, int $duration): mixedSends 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
| Parameter | Type | Description |
|---|---|---|
$identity | yii\ | |
$duration | int | Number of seconds that the user can remain in logged-in status. |
Returns
mixed
See also