How to Create and Enable Custom User Checkers
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 you 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 35 36 37 38 39 40
namespace App\Security;
use App\Entity\User as AppUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
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, ?TokenInterface $token = null): void
{
if (!$user instanceof AppUser) {
return;
}
// user account is expired, the user may be notified
if ($user->isExpired()) {
throw new AccountExpiredException('...');
}
if (!\in_array('foo', $token->getRoleNames())) {
throw new AccessDeniedException('...');
}
}
}
Warning
Symfony calls user checkers on every authentication, not only when users
submit a login form. This includes every time a "remember me" cookie
authenticates a user (on any URL of the application) and every request to a
stateless firewall. Symfony also calls
checkPostAuth() every time someone
impersonates a user. Keep user
checkers fast, don't use them to change the application state and don't
assume that the current request is a login request.
For example, to store the last login date of users, listen to the LoginSuccessEvent instead, which Symfony doesn't dispatch when impersonating users.
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
# ...
Running the User Checker When Users Are Refreshed
8.2
The user_checker_on_refresh option was introduced in Symfony 8.2.
User checkers only run when users authenticate, so an account disabled during a
session keeps working until the user logs out. Enable the
user_checker_on_refresh option to also run the user checker of the firewall
every time the user is refreshed from the session
and reject that account on the next request:
1 2 3 4 5 6 7 8 9 10
# config/packages/security.yaml
# ...
security:
firewalls:
main:
pattern: ^/
user_checker: App\Security\UserChecker
user_checker_on_refresh: true
# ...
When the user checker rejects the account, the user is logged out the same way as when their data changes. The exception thrown by the user checker is available in the TokenDeauthenticatedEvent, so you can tell users why they were logged out (see Adding Checks to the User Comparison).
When someone impersonates a user, only
checkPostAuth() runs, as it does when the impersonation starts.
This option requires a stateful firewall, because stateless firewalls never refresh users from the session.
Warning
With this option, the user checker runs on every request of the firewall, so enable it only if that checker is fast, doesn't change the application state and doesn't assume that the current request is a login request. If the firewall uses the chain user checker, keep in mind that packages installed later can add their own user checkers to that chain.
If you can't trust all the user checkers of a firewall, don't enable this option. Instead, register the RefreshedUserCheckerListener yourself with the user checker that you want to run on every request:
1 2 3 4 5 6 7 8 9 10
# config/services.yaml
# ...
services:
Symfony\Component\Security\Http\EventListener\RefreshedUserCheckerListener:
arguments: ['@App\Security\AccountEnabledUserChecker']
tags:
- name: kernel.event_listener
dispatcher: security.event_dispatcher.main
event: Symfony\Component\Security\Http\Event\CheckRefreshedUserEvent
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 }
Once your checker services are tagged, next you will need to 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
# ...