没有命名空间的类 yii yii\base yii\behaviors yii\caching yii\captcha yii\console yii\console\controllers yii\console\widgets yii\data yii\db yii\db\conditions yii\db\cubrid yii\db\cubrid\conditions yii\db\mssql yii\db\mssql\conditions yii\db\mysql yii\db\oci yii\db\oci\conditions yii\db\pgsql yii\db\sqlite yii\db\sqlite\conditions yii\di yii\filters yii\filters\auth yii\grid yii\helpers yii\i18n yii\log yii\mail yii\mutex yii\rbac yii\rest yii\test yii\validators yii\web yii\widgets

Class yii\web\User

继承yii\web\User » yii\base\Component » yii\base\BaseObject
实现yii\base\Configurable
可用版本自2.0
源码 https://github.com/yiichina/yii2/blob/api/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'],
    // ...
]

公共属性

隐藏继承的属性

属性类型描述被定义在
$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 The access checker to use for checking access. 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 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. 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. 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 The URL for login when loginRequired() is called. yii\web\User
$returnUrl string The URL that the user should be redirected to after login. yii\web\User
$returnUrlParam string The session variable name used to store the value of $returnUrl. yii\web\User

公共方法

隐藏继承的方法

方法描述被定义在
__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

受保护的方法

隐藏继承的方法

方法描述被定义在
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

常量

隐藏继承的常量

常量描述被定义在
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

属性详情

$absoluteAuthTimeout 公共 属性

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 公共 属性

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 公共 属性 (自版本 2.0.8 可用)

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

public array $acceptableRedirectTypes = ['text/html''application/xhtml+xml']
$accessChecker 公共 属性 (自版本 2.0.9 可用)

The access checker to use for checking access. If not set the application auth manager will be used.

$authTimeout 公共 属性

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.

public integer $authTimeout null
$authTimeoutParam 公共 属性

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 公共 属性

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.

参见 $enableAutoLogin.

public boolean $autoRenewCookie true
$enableAutoLogin 公共 属性

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 公共 属性

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 公共 只读 属性

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

public string|integer getId ( )
$idParam 公共 属性

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

public string $idParam '__id'
$identity 公共 属性

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

public yii\web\IdentityInterface|null getIdentity ( $autoRenew true )
public void setIdentity ( $identity )
$identityClass 公共 属性

The class name of the $identity object.

public string $identityClass null
$identityCookie 公共 属性

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

参见 yii\web\Cookie.

public array $identityCookie = ['name' => '_identity''httpOnly' => true]
$isGuest 公共 只读 属性

Whether the current user is a guest.

public boolean getIsGuest ( )
$loginUrl 公共 属性

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 $loginUrl = ['site/login']
$returnUrl 公共 属性

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

public string getReturnUrl ( $defaultUrl null )
public void setReturnUrl ( $url )
$returnUrlParam 公共 属性

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

public string $returnUrlParam '__returnUrl'

方法详情

afterLogin() 受保护 方法

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() 受保护 方法

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() 受保护 方法

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() 受保护 方法

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() 公共 方法

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() 受保护 方法 (自版本 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.

参见 $acceptableRedirectTypes.

protected boolean checkRedirectAcceptable()
return boolean

Whether this request may be redirected to the login page.

getAccessChecker() 受保护 方法 (自版本 2.0.9 可用)

Returns the access checker used for checking access.

protected yii\rbac\CheckAccessInterface getAccessChecker()
getAuthManager() 受保护 方法 (自版本 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() 公共 方法

Returns a value that uniquely represents the user.

参见 getIdentity().

public string|integer getId()
return string|integer

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

getIdentity() 公共 方法

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.

参见:

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() 受保护 方法 (自版本 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.

参见 loginByCookie().

protected array|null getIdentityAndDurationFromCookie()
return array|null

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

getIsGuest() 公共 方法

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

参见 getIdentity().

public boolean getIsGuest()
return boolean

Whether the current user is a guest.

getReturnUrl() 公共 方法

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.

参见 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.

init() 公共 方法

Initializes the application component.

public void init()
login() 公共 方法

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() 公共 方法

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() 受保护 方法

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() 公共 方法

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() 公共 方法

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() 受保护 方法 (自版本 2.0.14.2 可用)

Regenerates CSRF token

protected void regenerateCsrfToken()
removeIdentityCookie() 受保护 方法 (自版本 2.0.9 可用)

Removes the identity cookie.

This method is used when $enableAutoLogin is true.

protected void removeIdentityCookie()
renewAuthStatus() 受保护 方法

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() 受保护 方法

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() 受保护 方法

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.

参见 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() 公共 方法

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() 公共 方法

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() 公共 方法

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.