You are browsing the documentation for Symfony 3.1 which is not maintained anymore.
Consider upgrading your projects to Symfony 5.2.
How to Use Multiple Guard Authenticators
How to Use Multiple Guard Authenticators¶
The Guard authentication component allows you to easily use many different authenticators at a time.
An entry point is a service id (of one of your authenticators) whose
start()
method is called to start the authentication process.
Multiple Authenticators with Separate Entry Points¶
However, there are use cases where you have authenticators that protect different parts of your application. For example, you have a login form that protects the secured area of your application front-end and API end points that are protected with API tokens. As you can only configure one entry point per firewall, the solution is to split the configuration into two separate firewalls:
- YAML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# app/config/security.yml security: # ... firewalls: api: pattern: ^/api/ guard: authenticators: - app.api_token_authenticator default: anonymous: ~ guard: authenticators: - app.form_login_authenticator access_control: - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/api, roles: ROLE_API_USER } - { path: ^/, roles: ROLE_USER }
- XML
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
<!-- app/config/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 http://symfony.com/schema/dic/services/services-1.0.xsd"> <config> <!-- ... --> <firewall name="api" pattern="^/api/"> <guard> <authenticator>app.api_token_authenticator</authenticator> </guard> </firewall> <firewall name="default"> <anonymous /> <guard> <authenticator>app.form_login_authenticator</authenticator> </guard> </firewall> <rule path="^/login" role="IS_AUTHENTICATED_ANONYMOUSLY" /> <rule path="^/api" role="ROLE_API_USER" /> <rule path="^/" role="ROLE_USER" /> </config> </srv:container>
- PHP
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
// app/config/security.php $container->loadFromExtension('security', array( // ... 'firewalls' => array( 'api' => array( 'pattern' => '^/api', 'guard' => array( 'authenticators' => array( 'app.api_token_authenticator', ), ), ), 'default' => array( 'anonymous' => null, 'guard' => array( 'authenticators' => array( 'app.form_login_authenticator', ), ), ), ), 'access_control' => array( array('path' => '^/login', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY'), array('path' => '^/api', 'role' => 'ROLE_API_USER'), array('path' => '^/', 'role' => 'ROLE_USER'), ), ));
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.