Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Security
  4. How to Create and Enable Custom User Checkers

How to Create and Enable Custom User Checkers

Edit this page

During the authentication of a user, additional checks might be required to verify if the identified user is allowed to log in. By defining a custom user checker, you can define per firewall which checker should be used.

Creating a Custom User Checker

User checkers are classes that must implement the UserCheckerInterface. This interface defines two methods called checkPreAuth() and checkPostAuth() to perform checks before and after user authentication. If one or more conditions are not met, throw an exception which extends the AccountStatusException class. Consider using CustomUserMessageAccountStatusException, which extends AccountStatusException and allows to customize the error message displayed to the user:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
namespace App\Security;

use App\Entity\User as AppUser;
use Symfony\Component\Security\Core\Exception\AccountExpiredException;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class UserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user): void
    {
        if (!$user instanceof AppUser) {
            return;
        }

        if ($user->isDeleted()) {
            // the message passed to this exception is meant to be displayed to the user
            throw new CustomUserMessageAccountStatusException('Your user account no longer exists.');
        }
    }

    public function checkPostAuth(UserInterface $user): void
    {
        if (!$user instanceof AppUser) {
            return;
        }

        // user account is expired, the user may be notified
        if ($user->isExpired()) {
            throw new AccountExpiredException('...');
        }
    }
}

Enabling the Custom User Checker

Next, make sure your user checker is registered as a service. If you're using the default services.yaml configuration, the service is registered automatically.

All that's left to do is add the checker to the desired firewall where the value is the service id of your user checker:

1
2
3
4
5
6
7
8
9
# config/packages/security.yaml

# ...
security:
    firewalls:
        main:
            pattern: ^/
            user_checker: App\Security\UserChecker
            # ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- config/packages/security.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:srv="http://symfony.com/schema/dic/services"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/security
        https://symfony.com/schema/dic/security/security-1.0.xsd">

    <config>
        <!-- ... -->
        <firewall name="main"
                pattern="^/"
                user-checker="App\Security\UserChecker">
            <!-- ... -->
        </firewall>
    </config>
</srv:container>
1
2
3
4
5
6
7
8
9
10
11
12
// config/packages/security.php
use App\Security\UserChecker;
use Symfony\Config\SecurityConfig;

return static function (SecurityConfig $security): void {
    // ...
    $security->firewall('main')
        ->pattern('^/')
        ->userChecker(UserChecker::class)
        // ...
    ;
};

Using Multiple User Checkers

It is common for applications to have multiple authentication entry points (such as traditional form based login and an API) which may have unique checker rules for each entry point as well as common rules for all entry points. To allow using multiple user checkers on a firewall, a service for the ChainUserChecker class is created for each firewall.

To use the chain user checker, first you will need to tag your user checker services with the security.user_checker.<firewall> tag (where <firewall> is the name of the firewall in your security configuration). The service tag also supports the priority attribute, allowing you to define the order in which user checkers are called:

1
2
3
4
5
6
7
8
9
10
11
12
# config/services.yaml

# ...
services:
    App\Security\AccountEnabledUserChecker:
        tags:
            - { name: security.user_checker.api, priority: 10 }
            - { name: security.user_checker.main, priority: 10 }

    App\Security\APIAccessAllowedUserChecker:
        tags:
            - { name: security.user_checker.api, priority: 5 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <!-- ... -->

        <service id="App\Security\AccountEnabledUserChecker">
            <tag name="security.user_checker.api" priority="10"/>
            <tag name="security.user_checker.main" priority="10"/>
        </service>

        <service id="App\Security\APIAccessAllowedUserChecker">
            <tag name="security.user_checker.api" priority="5"/>
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use App\Security\AccountEnabledUserChecker;
use App\Security\APIAccessAllowedUserChecker;

return function(ContainerConfigurator $containerConfigurator) {
    $services = $containerConfigurator->services();

    $services->set(AccountEnabledUserChecker::class)
        ->tag('security.user_checker.api', ['priority' => 10])
        ->tag('security.user_checker.main', ['priority' => 10]);

    $services->set(APIAccessAllowedUserChecker::class)
        ->tag('security.user_checker.api', ['priority' => 5]);
};

Once your checker services are tagged, next you will need configure your firewalls to use the security.user_checker.chain.<firewall> service:

1
2
3
4
5
6
7
8
9
10
11
12
13
# config/packages/security.yaml

# ...
security:
    firewalls:
        api:
            pattern: ^/api
            user_checker: security.user_checker.chain.api
            # ...
        main:
            pattern: ^/
            user_checker: security.user_checker.chain.main
            # ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!-- config/packages/security.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:srv="http://symfony.com/schema/dic/services"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/security
        https://symfony.com/schema/dic/security/security-1.0.xsd">

    <config>
        <!-- ... -->
        <firewall name="api"
                pattern="^/api"
                user-checker="security.user_checker.chain.api">
            <!-- ... -->
        </firewall>
        <firewall name="main"
                pattern="^/"
                user-checker="security.user_checker.chain.main">
            <!-- ... -->
        </firewall>
    </config>
</srv:container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// config/packages/security.php
use Symfony\Config\SecurityConfig;

return static function (SecurityConfig $security): void {
    // ...
    $security->firewall('api')
        ->pattern('^/api')
        ->userChecker('security.user_checker.chain.api')
        // ...
    ;

    $security->firewall('main')
        ->pattern('^/')
        ->userChecker('security.user_checker.chain.main')
        // ...
    ;
};
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version

    Symfony 7.1 is backed by

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Save your teams and projects before they sink

    Save your teams and projects before they sink

    Version:

    Table of Contents

    • Creating a Custom User Checker
    • Enabling the Custom User Checker
    • Using Multiple User Checkers

    Symfony footer

    Avatar of sparrowek, a Symfony contributor

    Thanks sparrowek for being a Symfony contributor

    1 commit • 2 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony