PHPackages                             yiisoft/user - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. yiisoft/user

ActiveLibrary[Framework](/categories/framework)

yiisoft/user
============

Convenient user identity management and access checking

2.3.2(4mo ago)19130.9k—6.6%6[2 issues](https://github.com/yiisoft/user/issues)[1 PRs](https://github.com/yiisoft/user/pulls)2BSD-3-ClausePHPPHP 8.1 - 8.5CI passing

Since Dec 22Pushed 4mo ago12 watchersCompare

[ Source](https://github.com/yiisoft/user)[ Packagist](https://packagist.org/packages/yiisoft/user)[ Docs](https://www.yiiframework.com/)[ GitHub Sponsors](https://github.com/sponsors/yiisoft)[ OpenCollective](https://opencollective.com/yiisoft)[ RSS](/packages/yiisoft-user/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (20)Versions (10)Used By (2)

 [ ![Yii](https://camo.githubusercontent.com/8317c17418b39410a660f5149071d26c5023c0d5fb2b7ebb771324812f666d73/68747470733a2f2f796969736f66742e6769746875622e696f2f646f63732f696d616765732f7969695f6c6f676f2e737667) ](https://github.com/yiisoft)

Yii User
========

[](#yii-user)

[![Latest Stable Version](https://camo.githubusercontent.com/cf5c40addd19a294a86028f8044857127621d4ece2c94031eae2c15711bce008/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f757365722f76)](https://packagist.org/packages/yiisoft/user)[![Total Downloads](https://camo.githubusercontent.com/8e559731ca63707240f7daecd557515e7f32c261a09cb822ac4d1f48268d9bff/68747470733a2f2f706f7365722e707567782e6f72672f796969736f66742f757365722f646f776e6c6f616473)](https://packagist.org/packages/yiisoft/user)[![Build status](https://github.com/yiisoft/user/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/user/actions/workflows/build.yml)[![Code Coverage](https://camo.githubusercontent.com/67f2aa0e5af84202681226173845528b3f4f3f48f22e12ebc70107d96560c82d/68747470733a2f2f636f6465636f762e696f2f67682f796969736f66742f757365722f67726170682f62616467652e7376673f746f6b656e3d494c4e46565938433236)](https://codecov.io/gh/yiisoft/user)[![Mutation testing badge](https://camo.githubusercontent.com/09341b706bcbf8d759e12f809d5ddcbf24a02e2462ed5e846f8153540af68e9b/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d253246796969736f6674253246757365722532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/user/master)[![static analysis](https://github.com/yiisoft/user/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/user/actions?query=workflow%3A%22static+analysis%22)[![type-coverage](https://camo.githubusercontent.com/4e1a429e326356e19fbaaadc731f204774ce67d326d70bc57681f4c7ddc7cb06/68747470733a2f2f73686570686572642e6465762f6769746875622f796969736f66742f757365722f636f7665726167652e737667)](https://shepherd.dev/github/yiisoft/user)

The package handles user-related functionality:

- Login and logout.
- Getting currently logged in identity.
- Changing current identity.
- Access checking for current user.
- Auto login based on identity from request attribute.
- Auto login or "remember me" based on request cookie.

Requirements
------------

[](#requirements)

- PHP 8.1 - 8.5.

Installation
------------

[](#installation)

The package could be installed with [Composer](https://getcomposer.org):

```
composer require yiisoft/user
```

General usage
-------------

[](#general-usage)

This package is an addition to [yiisoft/auth](https://github.com/yiisoft/auth)and provides additional functionality for interacting with user identity.

### Working with identity

[](#working-with-identity)

The `CurrentUser` class is responsible for login and logout, as well as for providing data about the current user identity.

```
/**
 * @var \Psr\EventDispatcher\EventDispatcherInterface $eventDispatcher
 * @var \Yiisoft\Auth\IdentityRepositoryInterface $identityRepository
 */

$currentUser = new \Yiisoft\User\CurrentUser($identityRepository, $eventDispatcher);
```

If the user has not been logged in, then the current user is a guest:

```
$currentUser->getIdentity(); // \Yiisoft\User\Guest\GuestIdentity instance
$currentUser->getId(); // null
$currentUser->isGuest(); // bool
```

If you need to use a custom identity class to represent guest user, you should pass an instance of `GuestIdentityFactoryInterface` as a third optional parameter when creating `CurrentUser`:

```
/**
 * @var \Psr\EventDispatcher\EventDispatcherInterface $eventDispatcher
 * @var \Yiisoft\Auth\IdentityRepositoryInterface $identityRepository
 * @var \Yiisoft\User\Guest\GuestIdentityFactoryInterface $guestIdentityFactory
 */

$currentUser = new \Yiisoft\User\CurrentUser($identityRepository, $eventDispatcher, $guestIdentityFactory);
```

Also, you can override an identity instance in runtime:

```
/**
 * @var \Yiisoft\Auth\IdentityInterface $identity
 */

$currentUser->getIdentity(); // Original identity instance
$currentUser->overrideIdentity($identity);
$currentUser->getIdentity(); // Override identity instance
$currentUser->clearIdentityOverride();
$currentUser->getIdentity(); // Original identity instance
```

It can be useful to allow admin or developer to validate another user's problems.

#### Login and logout

[](#login-and-logout)

There are two methods for login and logout:

```
/**
 * @var \Yiisoft\Auth\IdentityInterface $identity
 */

$currentUser->getIdentity(); // GuestIdentityInterface instance

if ($currentUser->login($identity)) {
    $currentUser->getIdentity(); // $identity
    // Some actions
}

if ($currentUser->logout()) {
    $currentUser->getIdentity(); // GuestIdentityInterface instance
    // Some actions
}
```

Both methods trigger events. Events are of the following classes:

- `Yiisoft\User\Event\BeforeLogin` - triggered at the beginning of login process. Listeners of this event may call `$event->invalidate()` to cancel the login process.
- `Yiisoft\User\Event\AfterLogin` - triggered at the ending of login process.
- `Yiisoft\User\Event\BeforeLogout` - triggered at the beginning of logout process. Listeners of this event may call `$event->invalidate()` to cancel the logout process.
- `Yiisoft\User\Event\AfterLogout` - triggered at the ending of logout process.

Listeners of these events can get an identity instance participating in the process using `$event->getIdentity()`. Events are dispatched by `Psr\EventDispatcher\EventDispatcherInterface` instance, which is specified in the constructor when the `Yiisoft\User\CurrentUser` instance is initialized.

#### Checking user access

[](#checking-user-access)

To be able to check whether the current user can perform an operation corresponding to a given permission, you need to set an access checker (see [yiisoft/access](https://github.com/yiisoft/access)) instance:

```
/**
 * @var \Yiisoft\Access\AccessCheckerInterface $accessChecker
 */

$currentUser = $currentUser->withAccessChecker($accessChecker);
```

To perform the check, use `can()` method:

```
// The name of the permission (e.g. "edit post") that needs access check.
$permissionName = 'edit-post'; // Required.

// Name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user.
$params = ['postId' => 42]; // Optional. Default is empty array.

if ($currentUser->can($permissionName, $params)) {
    // Some actions
}
```

Note that in case access checker is not provided via `withAccessChecker()` method, `can()` will always return `false`.

#### Session usage

[](#session-usage)

The current user can store user ID and authentication timeouts for auto-login in the session. To do this, you need to provide a session (see [yiisoft/session](https://github.com/yiisoft/session)) instance:

```
/**
 * @var \Yiisoft\Session\SessionInterface $session
 */

$currentUser = $currentUser->withSession($session);
```

You can set timeout (number of seconds), during which the user will be logged out automatically in case of remaining inactive:

```
$currentUser = $currentUser->withAuthTimeout(3600);
```

Also, an absolute timeout (number of seconds) could be used. The user will be logged out automatically regardless of activity:

```
$currentUser = $currentUser->withAbsoluteAuthTimeout(3600);
```

By default, timeouts are not used, so the user will be logged out after the current session expires.

#### Using with event loop

[](#using-with-event-loop)

The `Yiisoft\User\CurrentUser` instance is stateful, so when you build long-running applications with tools like [Swoole](https://www.swoole.co.uk/) or [RoadRunner](https://roadrunner.dev/) you should reset the state at every request. For this purpose, you can use the `clear()` method.

### Authentication methods

[](#authentication-methods)

This package provides two authentication methods, `WebAuth` and `ApiAuth`, that implement the `Yiisoft\Auth\AuthenticationMethodInterface`. Both can be provided to the `Yiisoft\Auth\Authentication` middleware as authentication method.

#### WebAuth

[](#webauth)

`WebAuth` is used to authenticate users in the classic web applications. If authentication is failed, it creates a new instance of the response and adds a `Location` header with a temporary redirect to the authentication URL, by default `/login`.

You can change authentication URL by calling `WebAuth::withAuthUrl()` method:

```
use Yiisoft\User\Method\WebAuth;

$authenticationMethod = new WebAuth();

// Returns a new instance with the specified authentication URL.
$authenticationMethod = $authenticationMethod->withAuthUrl('/auth');
```

or in the [DI container](https://github.com/yiisoft/di):

```
// config/web/di/auth.php
return [
    WebAuth::class => [
        'withAuthUrl()' => ['/auth'],
    ],
];
```

or through the parameter `authUrl` of the `yiisoft/user` config group, [yiisoft/config](https://github.com/yiisoft/config) package must be installed:

```
// config/web/params.php
return [
    'yiisoft/user' => [
        'authUrl' => '/auth',
    ],
];
```

If the application is used along with the [yiisoft/config](https://github.com/yiisoft/config), the package is [configured](./config/di-web.php)automatically to use `WebAuth` as default implementation of `Yiisoft\Auth\AuthenticationMethodInterface`.

#### ApiAuth

[](#apiauth)

`ApiAuth` is used to authenticate users in the API clients. If authentication is failed, it returns the response from the `Yiisoft\Auth\Middleware\Authentication::authenticationFailureHandler` handler.

To use `ApiAuth` as an authentication method, you need or provide the `ApiAuth` instance to the `Yiisoft\Auth\Middleware\Authentication` middleware:

```
use Yiisoft\Auth\Middleware\Authentication;
use Yiisoft\User\Method\ApiAuth;

$authenticationMethod = new ApiAuth();

$middleware = new Authentication(
    $authenticationMethod,
    $responseFactory // PSR-17 ResponseFactoryInterface
);
```

of to define it as an implementation of `Yiisoft\Auth\AuthenticationMethodInterface` in the [DI container](https://github.com/yiisoft/di) configuration:

```
// config/web/di/auth.php
use Yiisoft\Auth\AuthenticationMethodInterface;
use Yiisoft\User\Method\ApiAuth;

return [
    AuthenticationMethodInterface::class => ApiAuth::class,
];
```

For more information about the authentication middleware and authentication methods, see the [yiisoft/auth](https://github.com/yiisoft/auth).

### Auto login through identity from request attribute

[](#auto-login-through-identity-from-request-attribute)

For auto login, you can use the `Yiisoft\User\Login\LoginMiddleware`. This middleware automatically logs user in if `Yiisoft\Auth\IdentityInterface` instance presents in a request attribute. It is usually put there by `Yiisoft\Auth\Middleware\Authentication`.

> Please note that `Yiisoft\Auth\Middleware\Authentication` should be located before `Yiisoft\User\Login\LoginMiddleware` in the middleware stack.

### Auto login through cookie

[](#auto-login-through-cookie)

In order to log user in automatically based on request cookie presence, use `Yiisoft\User\Login\Cookie\CookieLoginMiddleware`.

To use a middleware, you need to implement `Yiisoft\User\Login\Cookie\CookieLoginIdentityInterface`and also implement and use an instance of `IdentityRepositoryInterface` in the `CurrentUser`, which will return `CookieLoginIdentityInterface`:

```
use App\CookieLoginIdentity;
use Yiisoft\Auth\IdentityRepositoryInterface;

final class CookieLoginIdentityRepository implements IdentityRepositoryInterface
{
    private Storage $storage;

    public function __construct(Storage $storage)
    {
        $this->storage = $storage;
    }

    public function findIdentity(string $id): ?Identity
    {
        return new CookieLoginIdentity($this->storage->findOne($id));
    }
}
```

The `CookieLoginMiddleware` will check for the existence of a cookie in the request, validate it and login the user automatically.

#### Creating a cookie

[](#creating-a-cookie)

By default, you should set cookie for auto login manually in your application after logging user in:

```
public function login(
    \Psr\Http\Message\ServerRequestInterface $request,
    \Psr\Http\Message\ResponseFactoryInterface $responseFactory,
    \Yiisoft\User\Login\Cookie\CookieLogin $cookieLogin,
    \Yiisoft\User\CurrentUser $currentUser
): \Psr\Http\Message\ResponseInterface {
    $response = $responseFactory->createResponse();
    $body = $request->getParsedBody();

    // Get user identity based on body content.

    /** @var \Yiisoft\User\Login\Cookie\CookieLoginIdentityInterface $identity */

    if ($currentUser->login($identity) && ($body['rememberMe'] ?? false)) {
        $response = $cookieLogin->addCookie($identity, $response);
    }

    return $response;
}
```

In the above `rememberMe` in the request body may come from a "remember me" checkbox in the form. End user decides if he wants to be logged in automatically. If you do not need the user to be able to choose and want to always use "remember me", you can enable it via the `forceAddCookie` in `params.php`:

```
return [
    'yiisoft/user' => [
        'authUrl' => '/login',
        'cookieLogin' => [
            'forceAddCookie' => true,
            'duration' => 'P5D', // 5 days
        ],
    ],
];
```

> If you want the cookie to be a session cookie, change the duration to `null`.

#### Removing a cookie

[](#removing-a-cookie)

The `Yiisoft\User\Login\Cookie\CookieLoginMiddleware` automatically removes the cookie after the logout. But you can also remove the cookie manually:

```
public function logout(
    \Psr\Http\Message\ResponseFactoryInterface $responseFactory,
    \Yiisoft\User\Login\Cookie\CookieLogin $cookieLogin,
    \Yiisoft\User\CurrentUser $currentUser
): \Psr\Http\Message\ResponseInterface {
    $response = $responseFactory
        ->createResponse(302)
        ->withHeader('Location', '/');

    // Regenerate cookie login key to `Yiisoft\User\Login\Cookie\CookieLoginIdentityInterface` instance.

    if ($currentUser->logout()) {
        $response = $cookieLogin->expireCookie($response);
    }

    return $response;
}
```

#### Preventing the substitution of cookies

[](#preventing-the-substitution-of-cookies)

The login cookie value is stored raw. To prevent the substitution of the cookie value, you can use a `Yiisoft\Cookies\CookieMiddleware`. For more information, see [Yii guide to cookies](https://github.com/yiisoft/docs/blob/master/guide/en/runtime/cookies.md).

> Please note that `Yiisoft\Cookies\CookieMiddleware` should be located before `Yiisoft\User\Login\Cookie\CookieLoginMiddleware` in the middleware stack.

You can find examples of the above features in the [yiisoft/demo](https://github.com/yiisoft/demo).

Documentation
-------------

[](#documentation)

- [Internals](docs/internals.md)

If you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that. You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).

License
-------

[](#license)

The Yii User is free software. It is released under the terms of the BSD License. Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

Support the project
-------------------

[](#support-the-project)

[![Open Collective](https://camo.githubusercontent.com/a2b15f8e2268d4e3842e00d41ff7a57cce2ad8bd8d8769c5dc4fa05a546a4f62/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4f70656e253230436f6c6c6563746976652d73706f6e736f722d3765616466313f6c6f676f3d6f70656e253230636f6c6c656374697665266c6f676f436f6c6f723d376561646631266c6162656c436f6c6f723d353535353535)](https://opencollective.com/yiisoft)

Follow updates
--------------

[](#follow-updates)

[![Official website](https://camo.githubusercontent.com/d6b0929173e28cc627430d2519ca1853466a70f37395877eaf4820cb3e1e1909/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f506f77657265645f62792d5969695f4672616d65776f726b2d677265656e2e7376673f7374796c653d666c6174)](https://www.yiiframework.com/)[![Twitter](https://camo.githubusercontent.com/d077c362ac639792171af8bc002ee827816733dfc0925f70b557e6d151022226/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f747769747465722d666f6c6c6f772d3144413146323f6c6f676f3d74776974746572266c6f676f436f6c6f723d314441314632266c6162656c436f6c6f723d3535353535353f7374796c653d666c6174)](https://twitter.com/yiiframework)[![Telegram](https://camo.githubusercontent.com/4e38dd12535575c39c65bea7119b95e663abb2d1f4e3d669a27bbda07ef603f0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74656c656772616d2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d74656c656772616d)](https://t.me/yii3en)[![Facebook](https://camo.githubusercontent.com/48204e301b34b29b0815854544f04c337fc0692096cab35e9a1f8c53a42c2307/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f66616365626f6f6b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d66616365626f6f6b266c6f676f436f6c6f723d666666666666)](https://www.facebook.com/groups/yiitalk)[![Slack](https://camo.githubusercontent.com/1a3645ba1c97e6684d0349bc478201e1621ba0d3efad516d81035364d442bad7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736c61636b2d6a6f696e2d3144413146323f7374796c653d666c6174266c6f676f3d736c61636b)](https://yiiframework.com/go/slack)

###  Health Score

57

—

FairBetter than 98% of packages

Maintenance71

Regular maintenance activity

Popularity42

Moderate usage in the ecosystem

Community31

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor3

3 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~208 days

Recently: every ~186 days

Total

8

Last Release

147d ago

Major Versions

1.0.1 → 2.0.02023-02-15

PHP version history (5 changes)1.0.0PHP ^7.4|^8.0

2.1.0PHP ^8.0

2.2.0PHP ^8.1

2.3.0PHP ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0

2.3.2PHP 8.1 - 8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/261a6249c6f605f3956a2fae40fbb813f6b2e1e6f2bf806180c851a965426e54?d=identicon)[cebe](/maintainers/cebe)

![](https://www.gravatar.com/avatar/fc29e4e7068a00fe9b9db37b8aadda1db6020adcacef810461e47b99c2b150e6?d=identicon)[samdark](/maintainers/samdark)

![](https://www.gravatar.com/avatar/ccb75e3312d6bd454ea445ea308139fd185a4ca906ca5df21cc66e6a35de25a3?d=identicon)[SilverFire](/maintainers/SilverFire)

![](https://www.gravatar.com/avatar/99106256c24a8cb23871b99fa90e48f37f1aa71608c185759b7d2a88683a5918?d=identicon)[hiqsol](/maintainers/hiqsol)

---

Top Contributors

[![vjik](https://avatars.githubusercontent.com/u/525501?v=4)](https://github.com/vjik "vjik (33 commits)")[![samdark](https://avatars.githubusercontent.com/u/47294?v=4)](https://github.com/samdark "samdark (24 commits)")[![devanych](https://avatars.githubusercontent.com/u/20116244?v=4)](https://github.com/devanych "devanych (19 commits)")[![xepozz](https://avatars.githubusercontent.com/u/6815714?v=4)](https://github.com/xepozz "xepozz (15 commits)")[![rustamwin](https://avatars.githubusercontent.com/u/16498265?v=4)](https://github.com/rustamwin "rustamwin (9 commits)")[![roxblnfk](https://avatars.githubusercontent.com/u/4152481?v=4)](https://github.com/roxblnfk "roxblnfk (7 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (6 commits)")[![luizcmarin](https://avatars.githubusercontent.com/u/67489841?v=4)](https://github.com/luizcmarin "luizcmarin (2 commits)")[![viktorprogger](https://avatars.githubusercontent.com/u/7670669?v=4)](https://github.com/viktorprogger "viktorprogger (2 commits)")[![armpogart](https://avatars.githubusercontent.com/u/785768?v=4)](https://github.com/armpogart "armpogart (1 commits)")[![sankaest](https://avatars.githubusercontent.com/u/21160342?v=4)](https://github.com/sankaest "sankaest (1 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")[![terabytesoftw](https://avatars.githubusercontent.com/u/42547589?v=4)](https://github.com/terabytesoftw "terabytesoftw (1 commits)")[![olegbaturin](https://avatars.githubusercontent.com/u/15981018?v=4)](https://github.com/olegbaturin "olegbaturin (1 commits)")

---

Tags

hacktoberfestidentityloginlogoutremember-meuseryii3useryiisoft

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm, Rector

Type Coverage Yes

### Embed Badge

![Health badge](/badges/yiisoft-user/health.svg)

```
[![Health](https://phpackages.com/badges/yiisoft-user/health.svg)](https://phpackages.com/packages/yiisoft-user)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[yiisoft/yii-middleware

Yii Middleware

21151.3k1](/packages/yiisoft-yii-middleware)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[windwalker/framework

The next generation PHP framework.

25639.1k1](/packages/windwalker-framework)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
