# User

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

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [web](/docs/api/yii/web/index.md) › User

| class | `yii\web\User` |
| --- | --- |
| Extends | [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/web/User.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/web/User.php#L72) |

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

You may use [`$isGuest`](/docs/api/yii/web/user/index.md#property-isGuest) to determine whether the current user is a guest or not.
If the user is a guest, the [`$identity`](/docs/api/yii/web/user/index.md#property-identity) property would return `null`. Otherwise, it would
be an instance of [`IdentityInterface`](/docs/api/yii/web/identityinterface/index.md).

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

- [`login()`](/docs/api/yii/web/user/index.md#method-login): sets the specified identity and remembers the authentication status in session and cookie;
- [`logout()`](/docs/api/yii/web/user/index.md#method-logout): marks the user as a guest and clears the relevant information from session and cookie;
- [`setIdentity()`](/docs/api/yii/web/user/index.md#method-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`](/docs/api/yii/web/identityinterface/index.md).
You are also required to set [`$identityClass`](/docs/api/yii/web/user/index.md#property-identityClass) with the name of this class.

User is configured as an application component in [`Application`](/docs/api/yii/web/application/index.md) 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

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$absoluteAuthTimeout`](#property-absoluteAuthTimeout) | `int\|null` | The number of seconds in which the user will be logged out automatically regardless of activity. Default: `null`. | `User` |
| [`$absoluteAuthTimeoutParam`](#property-absoluteAuthTimeoutParam) | `string` | The session variable name used to store the value of absolute expiration timestamp of the authenticated state. Default: `'__absoluteExpire'`. | `User` |
| <span id="property-acceptableRedirectTypes"></span>`$acceptableRedirectTypes` | `array` | MIME types for which this component should redirect to the [`$loginUrl`](/docs/api/yii/web/user/index.md#property-loginUrl). Default: `['text/html', 'application/xhtml+xml']`. Available since 2.0.8. | `User` |
| [`$accessChecker`](#property-accessChecker) | [`yii\rbac\CheckAccessInterface`](/docs/api/yii/rbac/checkaccessinterface/index.md)`\|string\|array\|null` | 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` |
| <span id="property-authKeyParam"></span>`$authKeyParam` | `string` | The session variable name used to store authentication key. Default: `'__authKey'`. Available since 2.0.41. | `User` |
| [`$authTimeout`](#property-authTimeout) | `int\|null` | The number of seconds in which the user will be logged out automatically if the user remains inactive. Default: `null`. | `User` |
| [`$authTimeoutParam`](#property-authTimeoutParam) | `string` | The session variable name used to store the value of expiration timestamp of the authenticated state. Default: `'__expire'`. | `User` |
| [`$autoRenewCookie`](#property-autoRenewCookie) | `bool` | Whether to automatically renew the identity cookie each time a page is requested. Default: `true`. | `User` |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`$enableAutoLogin`](#property-enableAutoLogin) | `bool` | Whether to enable cookie-based login. Default: `false`. | `User` |
| [`$enableSession`](#property-enableSession) | `bool` | Whether to use session to persist authentication status across multiple requests. Default: `true`. | `User` |
| [`$id`](#property-id) read-only | `string\|int\|null` | The unique identifier for the user. | `User` |
| <span id="property-identity"></span>`$identity` | `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). | `User` |
| <span id="property-identityClass"></span>`$identityClass` | `class-string<yii\web\T>` | The class name of the [`$identity`](/docs/api/yii/web/user/index.md#property-identity) object. Default: `null`. | `User` |
| [`$identityCookie`](#property-identityCookie) | `array` | The configuration of the identity cookie. Default: `['name' => '_identity', 'httpOnly' => true]`. | `User` |
| <span id="property-idParam"></span>`$idParam` | `string` | The session variable name used to store the value of [`$id`](/docs/api/yii/web/user/index.md#property-id). Default: `'__id'`. | `User` |
| <span id="property-isGuest"></span>`$isGuest` read-only | `bool` | Whether the current user is a guest. | `User` |
| [`$loginUrl`](#property-loginUrl) | `string\|array\|null` | The URL for login when [`loginRequired()`](/docs/api/yii/web/user/index.md#method-loginRequired) is called. Default: `['site/login']`. | `User` |
| [`$returnUrl`](#property-returnUrl) | `string\|array` | The URL that the user should be redirected to after login. | `User` |
| <span id="property-returnUrlParam"></span>`$returnUrlParam` | `string` | The session variable name used to store the value of [`$returnUrl`](/docs/api/yii/web/user/index.md#property-returnUrl). Default: `'__returnUrl'`. | `User` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`can()`](#method-can) | Checks if the user can perform the operation as specified by the given permission. | `User` |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`checkRedirectAcceptable()`](#method-checkRedirectAcceptable) | Checks if the `Accept` header contains a content type that allows redirection to the login page. | `User` |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`getId()`](#method-getId) | Returns a value that uniquely represents the user. | `User` |
| [`getIdentity()`](#method-getIdentity) | Returns the identity object associated with the currently logged-in user. | `User` |
| [`getIsGuest()`](#method-getIsGuest) | Returns a value indicating whether the user is a guest (not authenticated). | `User` |
| [`getReturnUrl()`](#method-getReturnUrl) | Returns the URL that the browser should be redirected to after successful login. | `User` |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`init()`](#method-init) | Initializes the application component. | `User` |
| [`login()`](#method-login) | Logs in a user. | `User` |
| [`loginByAccessToken()`](#method-loginByAccessToken) | Logs in a user by the given access token. | `User` |
| [`loginRequired()`](#method-loginRequired) | Redirects the user browser to the login page. | `User` |
| [`logout()`](#method-logout) | Logs out the current user. | `User` |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`setIdentity()`](#method-setIdentity) | Sets the user identity object. | `User` |
| [`setReturnUrl()`](#method-setReturnUrl) | Remembers the URL in the session so that it can be retrieved back later by [`getReturnUrl()`](/docs/api/yii/web/user/index.md#method-getReturnUrl). | `User` |
| [`switchIdentity()`](#method-switchIdentity) | Switches to a new identity for the current user. | `User` |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`afterLogin()`](#method-afterLogin) protected | This method is called after the user is successfully logged in. | `User` |
| [`afterLogout()`](#method-afterLogout) protected | This method is invoked right after a user is logged out via [`logout()`](/docs/api/yii/web/user/index.md#method-logout). | `User` |
| [`beforeLogin()`](#method-beforeLogin) protected | This method is called before logging in a user. | `User` |
| [`beforeLogout()`](#method-beforeLogout) protected | This method is invoked when calling [`logout()`](/docs/api/yii/web/user/index.md#method-logout) to log out a user. | `User` |
| [`getAccessChecker()`](#method-getAccessChecker) protected | Returns the access checker used for checking access. | `User` |
| [`getIdentityAndDurationFromCookie()`](#method-getIdentityAndDurationFromCookie) protected | Determines if an identity cookie has a valid format and contains a valid auth key. | `User` |
| [`loginByCookie()`](#method-loginByCookie) protected | Logs in a user by cookie. | `User` |
| [`regenerateCsrfToken()`](#method-regenerateCsrfToken) protected | Regenerates CSRF token | `User` |
| [`removeIdentityCookie()`](#method-removeIdentityCookie) protected | Removes the identity cookie. | `User` |
| [`renewAuthStatus()`](#method-renewAuthStatus) protected | Updates the authentication status using the information from session and cookie. | `User` |
| [`renewIdentityCookie()`](#method-renewIdentityCookie) protected | Renews the identity cookie. | `User` |
| [`sendIdentityCookie()`](#method-sendIdentityCookie) protected | Sends an identity cookie. | `User` |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-EVENT_BEFORE_LOGIN"></span>`EVENT_BEFORE_LOGIN` | `'beforeLogin'` |  | `User` |
| <span id="const-EVENT_AFTER_LOGIN"></span>`EVENT_AFTER_LOGIN` | `'afterLogin'` |  | `User` |
| <span id="const-EVENT_BEFORE_LOGOUT"></span>`EVENT_BEFORE_LOGOUT` | `'beforeLogout'` |  | `User` |
| <span id="const-EVENT_AFTER_LOGOUT"></span>`EVENT_AFTER_LOGOUT` | `'afterLogout'` |  | `User` |

## Property details

### $absoluteAuthTimeout <span id="property-absoluteAuthTimeout"></span>

```php
public int|null $absoluteAuthTimeout = null
```

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

Note that this will not work if [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-enableAutoLogin) is `true`.

### $absoluteAuthTimeoutParam <span id="property-absoluteAuthTimeoutParam"></span>

```php
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`](/docs/api/yii/web/user/index.md#property-absoluteAuthTimeout) is set.

### $accessChecker <span id="property-accessChecker"></span>

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

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

If not set the application auth manager will be used.

**Since**

2.0.9

### $authTimeout <span id="property-authTimeout"></span>

```php
public int|null $authTimeout = null
```

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

If this property is not set, the user will be logged out after
the current session expires (c.f. [`Session::$timeout`](/docs/api/yii/web/session/index.md#property-timeout)).
Note that this will not work if [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-enableAutoLogin) is `true`.

### $authTimeoutParam <span id="property-authTimeoutParam"></span>

```php
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`](/docs/api/yii/web/user/index.md#property-authTimeout) is set.

### $autoRenewCookie <span id="property-autoRenewCookie"></span>

```php
public bool $autoRenewCookie = true
```

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

This property is effective only when [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-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 <span id="property-enableAutoLogin"></span>

```php
public bool $enableAutoLogin = false
```

Whether to enable cookie-based login.

Defaults to `false`.
Note that this property will be ignored if [`$enableSession`](/docs/api/yii/web/user/index.md#property-enableSession) is `false`.

### $enableSession <span id="property-enableSession"></span>

```php
public bool $enableSession = true
```

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

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

### $id <span id="property-id"></span>

```php
public string|int|null $id
```

The unique identifier for the user.

If `null`, it means the user is a
guest.

**Access**

Read-only (virtual property).

### $identityCookie <span id="property-identityCookie"></span>

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

The configuration of the identity cookie.

This property is used only when [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-enableAutoLogin) is `true`.

### $loginUrl <span id="property-loginUrl"></span>

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

The URL for login when [`loginRequired()`](/docs/api/yii/web/user/index.md#method-loginRequired) is called.

If an array is given, [`UrlManager::createUrl()`](/docs/api/yii/web/urlmanager/index.md#method-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()`](/docs/api/yii/web/user/index.md#method-loginRequired) is called.

### $returnUrl <span id="property-returnUrl"></span>

```php
public string|array $returnUrl
```

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

If an array is given, [`UrlManager::createUrl()`](/docs/api/yii/web/urlmanager/index.md#method-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

### can() <span id="method-can"></span>

```php
public function can(string $permissionName, array $params = [], bool $allowCaching = true): bool
```

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

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

**Parameters**

| 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()`](/docs/api/yii/rbac/checkaccessinterface/index.md#method-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() <span id="method-checkRedirectAcceptable"></span>

```php
public function checkRedirectAcceptable(): bool
```

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

The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable
content types by modifying [`$acceptableRedirectTypes`](/docs/api/yii/web/user/index.md#property-acceptableRedirectTypes) property.

**Returns**

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

**Since**

2.0.8

**See also**

- [`$acceptableRedirectTypes`](/docs/api/yii/web/user/index.md#property-acceptableRedirectTypes)

### getId() <span id="method-getId"></span>

```php
public function getId(): string|int|null
```

Returns a value that uniquely represents the user.

**Returns**

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

**See also**

- [`getIdentity()`](/docs/api/yii/web/user/index.md#method-getIdentity)

### getIdentity() <span id="method-getIdentity"></span>

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

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

When [`$enableSession`](/docs/api/yii/web/user/index.md#property-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`](/docs/api/yii/web/user/index.md#property-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**

- [`login()`](/docs/api/yii/web/user/index.md#method-login)
- [`logout()`](/docs/api/yii/web/user/index.md#method-logout)

### getIsGuest() <span id="method-getIsGuest"></span>

```php
public function getIsGuest(): bool
```

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

**Returns**

`bool`: Whether the current user is a guest.

**See also**

- [`getIdentity()`](/docs/api/yii/web/user/index.md#method-getIdentity)

### getReturnUrl() <span id="method-getReturnUrl"></span>

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

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

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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, [`Application::$homeUrl`](/docs/api/yii/web/application/index.md#property-homeUrl) will be redirected to. Please refer to [`setReturnUrl()`](/docs/api/yii/web/user/index.md#method-setReturnUrl) on accepted format of the URL. |

**Returns**

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

**See also**

- [`loginRequired()`](/docs/api/yii/web/user/index.md#method-loginRequired)

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Initializes the application component.

**Returns**

`mixed`

### login() <span id="method-login"></span>

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

Logs in a user.

After logging in a user:
- the user's identity information is obtainable from the [`$identity`](/docs/api/yii/web/user/index.md#property-identity) property

If [`$enableSession`](/docs/api/yii/web/user/index.md#property-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`](/docs/api/yii/web/user/index.md#property-enableAutoLogin) is set `true`.

If [`$enableSession`](/docs/api/yii/web/user/index.md#property-enableSession) is `false`:
- the `$duration` parameter will be ignored

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$identity` | `yii\web\T` | 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() <span id="method-loginByAccessToken"></span>

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

Logs in a user by the given access token.

This method will first authenticate the user by calling [`IdentityInterface::findIdentityByAccessToken()`](/docs/api/yii/web/identityinterface/index.md#method-findIdentityByAccessToken)
with the provided access token. If successful, it will call [`login()`](/docs/api/yii/web/user/index.md#method-login) to log in the authenticated user.
If authentication fails or [`login()`](/docs/api/yii/web/user/index.md#method-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`](/docs/api/yii/filters/auth/httpbearerauth/index.md) will set this parameter to be `yii\filters\auth\HttpBearerAuth`. |

**Returns**

`yii\web\T|null`: The identity associated with the given access token. Null is returned if the access token is invalid or [`login()`](/docs/api/yii/web/user/index.md#method-login) is unsuccessful.

### loginRequired() <span id="method-loginRequired"></span>

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

Redirects the user browser to the login page.

Before the redirection, the current URL (if it's not an AJAX url) will be kept as [`$returnUrl`](/docs/api/yii/web/user/index.md#property-returnUrl) so that
the user browser may be redirected back to the current page after successful login.

Make sure you set [`$loginUrl`](/docs/api/yii/web/user/index.md#property-loginUrl) so that the user browser can be redirected to the specified login URL after
calling this method.

Note that when [`$loginUrl`](/docs/api/yii/web/user/index.md#property-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`](/docs/api/yii/web/response/index.md): The redirection response if [`$loginUrl`](/docs/api/yii/web/user/index.md#property-loginUrl) is set

**Throws**

- [`ForbiddenHttpException`](/docs/api/yii/web/forbiddenhttpexception/index.md): the "Access Denied" HTTP exception if [`$loginUrl`](/docs/api/yii/web/user/index.md#property-loginUrl) is not set or a redirect is not applicable.

### logout() <span id="method-logout"></span>

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

Logs out the current user.

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$destroySession` | `bool` | Whether to destroy the whole session. Defaults to true. This parameter is ignored if [`$enableSession`](/docs/api/yii/web/user/index.md#property-enableSession) is false. |

**Returns**

`bool`: Whether the user is logged out

### setIdentity() <span id="method-setIdentity"></span>

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

Sets the user identity object.

Note that this method does not deal with session or cookie. You should usually use [`switchIdentity()`](/docs/api/yii/web/user/index.md#method-switchIdentity)
to change the identity of the current user.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$identity` | `yii\web\T\|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. |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidValueException`](/docs/api/yii/base/invalidvalueexception/index.md): if `$identity` object does not implement [`IdentityInterface`](/docs/api/yii/web/identityinterface/index.md).

### setReturnUrl() <span id="method-setReturnUrl"></span>

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

Remembers the URL in the session so that it can be retrieved back later by [`getReturnUrl()`](/docs/api/yii/web/user/index.md#method-getReturnUrl).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$url` | `string\|array` | The URL that the user should be redirected to after login. If an array is given, [`UrlManager::createUrl()`](/docs/api/yii/web/urlmanager/index.md#method-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() <span id="method-switchIdentity"></span>

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

Switches to a new identity for the current user.

When [`$enableSession`](/docs/api/yii/web/user/index.md#property-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()`](/docs/api/yii/web/user/index.md#method-login) for more details.

This method is mainly called by [`login()`](/docs/api/yii/web/user/index.md#method-login), [`logout()`](/docs/api/yii/web/user/index.md#method-logout) and [`loginByCookie()`](/docs/api/yii/web/user/index.md#method-loginByCookie)
when the current user needs to be associated with the corresponding identity information.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$identity` | `yii\web\T\|null` | 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() <span id="method-afterLogin"></span>

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

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

The default implementation will trigger the [`EVENT_AFTER_LOGIN`](/docs/api/yii/web/user/index.md#const-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\web\T` | 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() <span id="method-afterLogout"></span>

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

This method is invoked right after a user is logged out via [`logout()`](/docs/api/yii/web/user/index.md#method-logout).

The default implementation will trigger the [`EVENT_AFTER_LOGOUT`](/docs/api/yii/web/user/index.md#const-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\web\T` | The user identity information |

**Returns**

`mixed`

### beforeLogin() <span id="method-beforeLogin"></span>

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

This method is called before logging in a user.

The default implementation will trigger the [`EVENT_BEFORE_LOGIN`](/docs/api/yii/web/user/index.md#const-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\web\T` | 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() <span id="method-beforeLogout"></span>

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

This method is invoked when calling [`logout()`](/docs/api/yii/web/user/index.md#method-logout) to log out a user.

The default implementation will trigger the [`EVENT_BEFORE_LOGOUT`](/docs/api/yii/web/user/index.md#const-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\web\T` | The user identity information |

**Returns**

`bool`: Whether the user should continue to be logged out

### getAccessChecker() <span id="method-getAccessChecker"></span>

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

Returns the access checker used for checking access.

**Returns**

[`yii\rbac\CheckAccessInterface`](/docs/api/yii/rbac/checkaccessinterface/index.md)`|null`

**Since**

2.0.9

### getIdentityAndDurationFromCookie() <span id="method-getIdentityAndDurationFromCookie"></span>

```php
protected function getIdentityAndDurationFromCookie(): array|null
```

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

This method is used when [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-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()`](/docs/api/yii/web/user/index.md#method-loginByCookie)

### loginByCookie() <span id="method-loginByCookie"></span>

```php
protected function loginByCookie(): mixed
```

Logs in a user by cookie.

This method attempts to log in a user using the ID and authKey information
provided by the [identity cookie](/docs/api/yii/web/user/index.md#property-identityCookie).

**Returns**

`mixed`

### regenerateCsrfToken() <span id="method-regenerateCsrfToken"></span>

```php
protected function regenerateCsrfToken(): mixed
```

Regenerates CSRF token

**Returns**

`mixed`

**Since**

2.0.14.2

### removeIdentityCookie() <span id="method-removeIdentityCookie"></span>

```php
protected function removeIdentityCookie(): mixed
```

Removes the identity cookie.

This method is used when [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-enableAutoLogin) is true.

**Returns**

`mixed`

**Since**

2.0.9

### renewAuthStatus() <span id="method-renewAuthStatus"></span>

```php
protected function renewAuthStatus(): mixed
```

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

This method will try to determine the user identity using the [`$idParam`](/docs/api/yii/web/user/index.md#property-idParam) session variable.

If [`$authTimeout`](/docs/api/yii/web/user/index.md#property-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](/docs/api/yii/web/user/index.md#method-loginByCookie)
if [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-enableAutoLogin) is true.

**Returns**

`mixed`

### renewIdentityCookie() <span id="method-renewIdentityCookie"></span>

```php
protected function renewIdentityCookie(): mixed
```

Renews the identity cookie.

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

**Returns**

`mixed`

### sendIdentityCookie() <span id="method-sendIdentityCookie"></span>

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

Sends an identity cookie.

This method is used when [`$enableAutoLogin`](/docs/api/yii/web/user/index.md#property-enableAutoLogin) is true.
It saves [`$id`](/docs/api/yii/web/user/index.md#property-id), [auth key](/docs/api/yii/web/identityinterface/index.md#method-getAuthKey), and the duration of cookie-based login
information in the cookie.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$identity` | `yii\web\T` |  |
| `$duration` | `int` | Number of seconds that the user can remain in logged-in status. |

**Returns**

`mixed`

**See also**

- [`loginByCookie()`](/docs/api/yii/web/user/index.md#method-loginByCookie)