Class yii\web\User

Inheritanceyii\web\User » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/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 yii\web\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 yii\web\IdentityInterface. You are also required to set $identityClass with the name of this class.

User is configured as an application component in yii\web\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'],
    // ...
]

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$absoluteAuthTimeout integer|null The number of seconds in which the user will be logged out automatically regardless of activity. yii\web\User
$absoluteAuthTimeoutParam string The session variable name used to store the value of absolute expiration timestamp of the authenticated state. yii\web\User
$acceptableRedirectTypes array MIME types for which this component should redirect to the $loginUrl. yii\web\User
$accessChecker yii\rbac\CheckAccessInterface|string|array|null The access checker object to use for checking access or the application component ID of the access checker. yii\web\User
$authKeyParam string The session variable name used to store authentication key. yii\web\User
$authTimeout integer|null The number of seconds in which the user will be logged out automatically if the user remains inactive. yii\web\User
$authTimeoutParam string The session variable name used to store the value of expiration timestamp of the authenticated state. yii\web\User
$autoRenewCookie boolean Whether to automatically renew the identity cookie each time a page is requested. yii\web\User
$behaviors yii\base\Behavior[] List of behaviors attached to this component. yii\base\Component
$enableAutoLogin boolean Whether to enable cookie-based login. yii\web\User
$enableSession boolean Whether to use session to persist authentication status across multiple requests. yii\web\User
$id string|integer The unique identifier for the user. If null, it means the user is a guest. yii\web\User
$idParam string The session variable name used to store the value of $id. yii\web\User
$identity yii\web\IdentityInterface|null The identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated). yii\web\User
$identityClass string The class name of the $identity object. yii\web\User
$identityCookie array The configuration of the identity cookie. yii\web\User
$isGuest boolean Whether the current user is a guest. yii\web\User
$loginUrl string|array|null The URL for login when loginRequired() is called. yii\web\User
$returnUrl string The URL that the user should be redirected to after login. Note that the type of this property differs in getter and setter. See getReturnUrl() and setReturnUrl() for details. yii\web\User
$returnUrlParam string The session variable name used to store the value of $returnUrl. yii\web\User

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__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
__construct() Constructor. yii\base\BaseObject
__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. yii\web\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. yii\web\User
className() Returns 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. yii\web\User
getIdentity() Returns the identity object associated with the currently logged-in user. yii\web\User
getIsGuest() Returns a value indicating whether the user is a guest (not authenticated). yii\web\User
getReturnUrl() Returns the URL that the browser should be redirected to after successful login. yii\web\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. yii\web\User
login() Logs in a user. yii\web\User
loginByAccessToken() Logs in a user by the given access token. yii\web\User
loginRequired() Redirects the user browser to the login page. yii\web\User
logout() Logs out the current user. yii\web\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. yii\web\User
setReturnUrl() Remembers the URL in the session so that it can be retrieved back later by getReturnUrl(). yii\web\User
switchIdentity() Switches to a new identity for the current user. yii\web\User
trigger() Triggers an event. yii\base\Component

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
afterLogin() This method is called after the user is successfully logged in. yii\web\User
afterLogout() This method is invoked right after a user is logged out via logout(). yii\web\User
beforeLogin() This method is called before logging in a user. yii\web\User
beforeLogout() This method is invoked when calling logout() to log out a user. yii\web\User
getAccessChecker() Returns the access checker used for checking access. yii\web\User
getAuthManager() Returns auth manager associated with the user component. yii\web\User
getIdentityAndDurationFromCookie() Determines if an identity cookie has a valid format and contains a valid auth key. yii\web\User
loginByCookie() Logs in a user by cookie. yii\web\User
regenerateCsrfToken() Regenerates CSRF token yii\web\User
removeIdentityCookie() Removes the identity cookie. yii\web\User
renewAuthStatus() Updates the authentication status using the information from session and cookie. yii\web\User
renewIdentityCookie() Renews the identity cookie. yii\web\User
sendIdentityCookie() Sends an identity cookie. yii\web\User

Constants

Hide inherited constants

ConstantValueDescriptionDefined By
EVENT_AFTER_LOGIN 'afterLogin' yii\web\User
EVENT_AFTER_LOGOUT 'afterLogout' yii\web\User
EVENT_BEFORE_LOGIN 'beforeLogin' yii\web\User
EVENT_BEFORE_LOGOUT 'beforeLogout' yii\web\User

Property Details

$absoluteAuthTimeout public property

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.

$absoluteAuthTimeoutParam public property

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 string $absoluteAuthTimeoutParam '__absoluteExpire'
$acceptableRedirectTypes public property (available since version 2.0.8)

MIME types for which this component should redirect to the $loginUrl.

public array $acceptableRedirectTypes = [
    'text/html''application/xhtml+xml'
]
$accessChecker public property (available since version 2.0.9)

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.

$authKeyParam public property (available since version 2.0.41)

The session variable name used to store authentication key.

public string $authKeyParam '__authKey'
$authTimeout public property

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. yii\web\Session::$timeout). Note that this will not work if $enableAutoLogin is true.

public integer|null $authTimeout null
$authTimeoutParam public property

The session variable name used to store the value of expiration timestamp of the authenticated state. This is used when $authTimeout is set.

public string $authTimeoutParam '__expire'
$autoRenewCookie public property

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.

See also $enableAutoLogin.

public boolean $autoRenewCookie true
$enableAutoLogin public property

Whether to enable cookie-based login. Defaults to false. Note that this property will be ignored if $enableSession is false.

public boolean $enableAutoLogin false
$enableSession public property

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 boolean $enableSession true
$id public property

The unique identifier for the user. If null, it means the user is a guest.

public string|integer $id null
$idParam public property

The session variable name used to store the value of $id.

public string $idParam '__id'
$identity public property

The identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated).

$identityClass public property

The class name of the $identity object.

public string $identityClass null
$identityCookie public property

The configuration of the identity cookie. This property is used only when $enableAutoLogin is true.

See also yii\web\Cookie.

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

Whether the current user is a guest.

public boolean $isGuest null
$loginUrl public property

The URL for login when loginRequired() is called. If an array is given, yii\web\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|null $loginUrl = [
    'site/login'
]
$returnUrl public property

The URL that the user should be redirected to after login. Note that the type of this property differs in getter and setter. See getReturnUrl() and setReturnUrl() for details.

public string $returnUrl null
$returnUrlParam public property

The session variable name used to store the value of $returnUrl.

public string $returnUrlParam '__returnUrl'

Method Details

afterLogin() protected method

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.

protected void afterLogin ( $identity, $cookieBased, $duration )
$identity yii\web\IdentityInterface

The user identity information

$cookieBased boolean

Whether the login is cookie-based

$duration integer

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.

afterLogout() protected method

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.

protected void afterLogout ( $identity )
$identity yii\web\IdentityInterface

The user identity information

beforeLogin() protected method

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.

protected boolean beforeLogin ( $identity, $cookieBased, $duration )
$identity yii\web\IdentityInterface

The user identity information

$cookieBased boolean

Whether the login is cookie-based

$duration integer

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.

return boolean

Whether the user should continue to be logged in

beforeLogout() protected method

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.

protected boolean beforeLogout ( $identity )
$identity yii\web\IdentityInterface

The user identity information

return boolean

Whether the user should continue to be logged out

can() public method

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.

public boolean can ( $permissionName, $params = [], $allowCaching true )
$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 boolean

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 yii\rbac\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 = [].

return boolean

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

checkRedirectAcceptable() public method (available since version 2.0.8)

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.

See also $acceptableRedirectTypes.

public boolean checkRedirectAcceptable ( )
return boolean

Whether this request may be redirected to the login page.

getAccessChecker() protected method (available since version 2.0.9)

Returns the access checker used for checking access.

protected yii\rbac\CheckAccessInterface getAccessChecker ( )
getAuthManager() protected method (available since version 2.0.6)
Deprecated since version 2.0.9, to be removed in 2.1. Use getAccessChecker() instead.

Returns auth manager associated with the user component.

By default this is the authManager application component. You may override this method to return a different auth manager instance if needed.

protected yii\rbac\ManagerInterface getAuthManager ( )
getId() public method

Returns a value that uniquely represents the user.

See also getIdentity().

public string|integer|null getId ( )
return string|integer|null

The unique identifier for the user. If null, it means the user is a guest.

getIdentity() public method

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.

See also:

public yii\web\IdentityInterface|null getIdentity ( $autoRenew true )
$autoRenew boolean

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

return yii\web\IdentityInterface|null

The identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated).

getIdentityAndDurationFromCookie() protected method (available since version 2.0.9)

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.

See also loginByCookie().

protected array|null getIdentityAndDurationFromCookie ( )
return array|null

Returns an array of 'identity' and 'duration' if valid, otherwise null.

getIsGuest() public method

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

See also getIdentity().

public boolean getIsGuest ( )
return boolean

Whether the current user is a guest.

getReturnUrl() public method

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.

See also loginRequired().

public string getReturnUrl ( $defaultUrl null )
$defaultUrl string|array|null

The default return URL in case it was not set previously. If this is null and the return URL was not set previously, yii\web\Application::$homeUrl will be redirected to. Please refer to setReturnUrl() on accepted format of the URL.

return string

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

init() public method

Initializes the application component.

public void init ( )
login() public method

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
public boolean login ( yii\web\IdentityInterface $identity, $duration 0 )
$identity yii\web\IdentityInterface

The user identity (which should already be authenticated)

$duration integer

Number of seconds that the user can remain in logged-in status, defaults to 0

return boolean

Whether the user is logged in

loginByAccessToken() public method

Logs in a user by the given access token.

This method will first authenticate the user by calling yii\web\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.

public yii\web\IdentityInterface|null loginByAccessToken ( $token, $type null )
$token string

The access token

$type mixed

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

return yii\web\IdentityInterface|null

The identity associated with the given access token. Null is returned if the access token is invalid or login() is unsuccessful.

loginByCookie() protected method

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.

protected void loginByCookie ( )
loginRequired() public method

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.

public yii\web\Response loginRequired ( $checkAjax true, $checkAcceptHeader true )
$checkAjax boolean

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 boolean

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.

return yii\web\Response

The redirection response if $loginUrl is set

throws yii\web\ForbiddenHttpException

the "Access Denied" HTTP exception if $loginUrl is not set or a redirect is not applicable.

logout() public method

Logs out the current user.

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

public boolean logout ( $destroySession true )
$destroySession boolean

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

return boolean

Whether the user is logged out

regenerateCsrfToken() protected method (available since version 2.0.14.2)

Regenerates CSRF token

protected void regenerateCsrfToken ( )
removeIdentityCookie() protected method (available since version 2.0.9)

Removes the identity cookie.

This method is used when $enableAutoLogin is true.

protected void removeIdentityCookie ( )
renewAuthStatus() protected method

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.

protected void renewAuthStatus ( )
renewIdentityCookie() protected method

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.

protected void renewIdentityCookie ( )
sendIdentityCookie() protected method

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.

See also loginByCookie().

protected void sendIdentityCookie ( $identity, $duration )
$identity yii\web\IdentityInterface
$duration integer

Number of seconds that the user can remain in logged-in status.

setIdentity() public method

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.

public void setIdentity ( $identity )
$identity yii\web\IdentityInterface|null

The identity object associated with the currently logged user. If null, it means the current user will be a guest without any associated identity.

throws yii\base\InvalidValueException

if $identity object does not implement yii\web\IdentityInterface.

setReturnUrl() public method

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

public void setReturnUrl ( $url )
$url string|array

The URL that the user should be redirected to after login. If an array is given, yii\web\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]
switchIdentity() public method

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.

public void switchIdentity ( $identity, $duration 0 )
$identity yii\web\IdentityInterface|null

The identity information to be associated with the current user. If null, it means switching the current user to be a guest.

$duration integer

Number of seconds that the user can remain in logged-in status. This parameter is used only when $identity is not null.