Class yii\web\User
Inheritance | yii\web\User » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Available since version | 2.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
Property | Type | Description | Defined By |
---|---|---|---|
$absoluteAuthTimeout | integer | 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 | The access checker object to use for checking access or the application component ID of the access checker. | yii\web\User |
$authTimeout | integer | The number of seconds in which the user will be logged out automatically if he 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. This property is read-only. | 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.
This property is read-only. |
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. This property is read-only. | yii\web\User |
$loginUrl | string|array | 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
Method | Description | Defined 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 |
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
Method | Description | Defined 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 |
checkRedirectAcceptable() | Checks if the Accept header contains a content type that allows redirection to the login page. |
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
Constant | Value | Description | Defined 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
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
.
The session variable name used to store the value of absolute expiration timestamp of the authenticated state. This is used when $absoluteAuthTimeout is set.
MIME types for which this component should redirect to the $loginUrl.
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.
The number of seconds in which the user will be logged out automatically if he
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
.
The session variable name used to store the value of expiration timestamp of the authenticated state. This is used when $authTimeout is set.
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.
Whether to enable cookie-based login. Defaults to false
.
Note that this property will be ignored if $enableSession is false
.
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.
The unique identifier for the user. If null
, it means the user is a guest.
This property is read-only.
The session variable name used to store the value of $id.
The identity object associated with the currently logged-in
user. null
is returned if the user is not logged in (not authenticated).
The class name of the $identity object.
The configuration of the identity cookie. This property is used only when $enableAutoLogin is true
.
See also yii\web\Cookie.
Whether the current user is a guest. This property is read-only.
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.
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.
The session variable name used to store the value of $returnUrl.
Method Details
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. |
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 |
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 |
---|
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 |
---|
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 |
return | boolean | Whether the user can perform the operation as specified by the given permission. |
---|
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.
protected boolean checkRedirectAcceptable ( ) | ||
return | boolean | Whether this request may be redirected to the login page. |
---|
Returns the access checker used for checking access.
protected yii\rbac\CheckAccessInterface getAccessChecker ( ) |
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 ( ) |
Returns a value that uniquely represents the user.
See also getIdentity().
public string|integer getId ( ) | ||
return | string|integer | The unique identifier for the user. If |
---|
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.
|
---|
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. |
---|
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. |
---|
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 | 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. |
---|
Initializes the application component.
public void init ( ) |
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 settrue
.
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 |
return | boolean | Whether the user is logged in |
---|
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 |
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. |
---|
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 ( ) |
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 |
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. |
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 |
---|
Regenerates CSRF token
protected void regenerateCsrfToken ( ) |
Removes the identity cookie.
This method is used when $enableAutoLogin is true.
protected void removeIdentityCookie ( ) |
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 ( ) |
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 ( ) |
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. |
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 |
---|
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,
|
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 |
Signup or Login in order to comment.