Security Configuration Reference (SecurityBundle)

Security Configuration Reference (SecurityBundle)

The SecurityBundle integrates the Security component in Symfony applications. All these options are configured under the security key in your application configuration.

  1. # displays the default config values defined by Symfony
  2. $ php bin/console config:dump-reference security
  3. # displays the actual config values used by your application
  4. $ php bin/console debug:config security

Note

When using XML, you must use the http://symfony.com/schema/dic/security namespace and the related XSD schema is available at: https://symfony.com/schema/dic/services/services-1.0.xsd

Configuration

Basic Options:

Advanced Options:

Some of these options define tens of sub-options and they are explained in separate articles:

access_denied_url

type: string default: null

Defines the URL where the user is redirected after a 403 HTTP error (unless you define a custom access deny handler). Example: /no-permission

always_authenticate_before_granting

type: boolean default: false

If true, the user is asked to authenticate before each call to the isGranted() method in services and controllers or is_granted() from templates.

anonymous

type: string default: ~

When set to lazy, Symfony loads the user (and starts the session) only if the application actually accesses the User object (e.g. via a is_granted() call in a template or isGranted() in a controller or service).

New in version 4.4: The lazy value of the anonymous option was introduced in Symfony 4.4.

erase_credentials

type: boolean default: true

If true, the eraseCredentials() method of the user object is called after authentication.

hide_user_not_found

type: boolean default: true

If true, when a user is not found a generic exception of type Symfony\Component\Security\Core\Exception\BadCredentialsException is thrown with the message “Bad credentials”.

If false, the exception thrown is of type Symfony\Component\Security\Core\Exception\UsernameNotFoundException and it includes the given not found username.

session_fixation_strategy

type: string default: SessionAuthenticationStrategy::MIGRATE

Session Fixation is a security attack that permits an attacker to hijack a valid user session. Applications that don’t assign new session IDs when authenticating users are vulnerable to this attack.

The possible values of this option are:

  • NONE constant from Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy Don’t change the session after authentication. This is not recommended.
  • MIGRATE constant from Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy The session ID is updated, but the rest of session attributes are kept.
  • INVALIDATE constant from Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy The entire session is regenerated, so the session ID is updated but all the other session attributes are lost.

access_control

Defines the security protection of the URLs of your application. It’s used for example to trigger the user authentication when trying to access to the backend and to allow anonymous users to the login form page.

This option is explained in detail in How Does the Security access_control Work?.

encoders

This option defines the algorithm used to encode the password of the users. Although Symfony calls it “password encoding” for historical reasons, this is in fact, “password hashing”.

If your app defines more than one user class, each of them can define its own encoding algorithm. Also, each algorithm defines different config options:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. encoders:
    5. # auto encoder with default options
    6. App\Entity\User: 'auto'
    7. # auto encoder with custom options
    8. App\Entity\User:
    9. algorithm: 'auto'
    10. cost: 15
    11. # Sodium encoder with default options
    12. App\Entity\User: 'sodium'
    13. # Sodium encoder with custom options
    14. App\Entity\User:
    15. algorithm: 'sodium'
    16. memory_cost: 16384 # Amount in KiB. (16384 = 16 MiB)
    17. time_cost: 2 # Number of iterations
    18. threads: 4 # Number of parallel threads
    19. # MessageDigestPasswordEncoder encoder using SHA512 hashing with default options
    20. App\Entity\User: 'sha512'
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <!-- auto encoder with default options -->
    11. <encoder
    12. class="App\Entity\User"
    13. algorithm="auto"
    14. />
    15. <!-- auto encoder with custom options -->
    16. <encoder
    17. class="App\Entity\User"
    18. algorithm="auto"
    19. cost="15"
    20. />
    21. <!-- Sodium encoder with default options -->
    22. <encoder
    23. class="App\Entity\User"
    24. algorithm="sodium"
    25. />
    26. <!-- Sodium encoder with custom options -->
    27. <!-- memory_cost: amount in KiB. (16384 = 16 MiB)
    28. time_cost: number of iterations
    29. threads: number of parallel threads -->
    30. <encoder
    31. class="App\Entity\User"
    32. algorithm="sodium"
    33. memory_cost="16384"
    34. time_cost="2"
    35. threads="4"
    36. />
    37. <!-- MessageDigestPasswordEncoder encoder using SHA512 hashing with default options -->
    38. <encoder
    39. class="App\Entity\User"
    40. algorithm="sha512"
    41. />
    42. </config>
    43. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. use App\Entity\User;
    3. $container->loadFromExtension('security', [
    4. // ...
    5. 'encoders' => [
    6. // auto encoder with default options
    7. User::class => [
    8. 'algorithm' => 'auto',
    9. ],
    10. // auto encoder with custom options
    11. User::class => [
    12. 'algorithm' => 'auto',
    13. 'cost' => 15,
    14. ],
    15. // Sodium encoder with default options
    16. User::class => [
    17. 'algorithm' => 'sodium',
    18. ],
    19. // Sodium encoder with custom options
    20. User::class => [
    21. 'algorithm' => 'sodium',
    22. 'memory_cost' => 16384, // Amount in KiB. (16384 = 16 MiB)
    23. 'time_cost' => 2, // Number of iterations
    24. 'threads' => 4, // Number of parallel threads
    25. ],
    26. // MessageDigestPasswordEncoder encoder using SHA512 hashing with default options
    27. User::class => [
    28. 'algorithm' => 'sha512',
    29. ],
    30. ],
    31. ]);

Deprecated since version 4.3: The threads configuration option was deprecated in Symfony 4.3. No alternative is provided because starting from Symfony 5.0 this value will be hardcoded to 1 (one thread).

New in version 4.3: The sodium algorithm was introduced in Symfony 4.3. In previous Symfony versions it was called argon2i.

Tip

You can also create your own password encoders as services and you can even select a different password encoder for each user instance. Read this article for more details.

Using the Sodium Password Encoder

New in version 4.3: The SodiumPasswordEncoder was introduced in Symfony 4.3. In previous Symfony versions it was called Argon2iPasswordEncoder.

It uses the Argon2 key derivation function and it’s the encoder recommended by Symfony. Argon2 support was introduced in PHP 7.2, but if you use an earlier PHP version, you can install the libsodium PHP extension.

The encoded passwords are 96 characters long, but due to the hashing requirements saved in the resulting hash this may change in the future, so make sure to allocate enough space for them to be persisted. Also, passwords include the cryptographic salt) inside them (it’s generated automatically for each new password) so you don’t have to deal with it.

Using the “auto” Password Encoder

It selects automatically the best possible encoder. Currently, it tries to use Sodium by default and falls back to the bcrypt password hashing function if not possible. In the future, when PHP adds new hashing techniques, it may use different password hashers.

It produces encoded passwords with 60 characters long, so make sure to allocate enough space for them to be persisted. Also, passwords include the cryptographic salt) inside them (it’s generated automatically for each new password) so you don’t have to deal with it.

Its only configuration option is cost, which is an integer in the range of 4-31 (by default, 13). Each single increment of the cost doubles the time it takes to encode a password. It’s designed this way so the password strength can be adapted to the future improvements in computation power.

You can change the cost at any time — even if you already have some passwords encoded using a different cost. New passwords will be encoded using the new cost, while the already encoded ones will be validated using a cost that was used back when they were encoded.

Tip

A simple technique to make tests much faster when using BCrypt is to set the cost to 4, which is the minimum value allowed, in the test environment configuration.

Using the PBKDF2 Encoder

Using the PBKDF2 encoder is no longer recommended since PHP added support for Sodium and BCrypt. Legacy application still using it are encouraged to upgrade to those newer encoding algorithms.

firewalls

This is arguably the most important option of the security config file. It defines the authentication mechanism used for each URL (or URL pattern) of your application:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. # 'main' is the name of the firewall (can be chosen freely)
    6. main:
    7. # 'pattern' is a regular expression matched against the incoming
    8. # request URL. If there's a match, authentication is triggered
    9. pattern: ^/admin
    10. # the rest of options depend on the authentication mechanism
    11. # ...
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <!-- 'pattern' is a regular expression matched against the incoming
    11. request URL. If there's a match, authentication is triggered -->
    12. <firewall name="main" pattern="^/admin">
    13. <!-- the rest of options depend on the authentication mechanism -->
    14. <!-- ... -->
    15. </firewall>
    16. </config>
    17. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. // ...
    3. $container->loadFromExtension('security', [
    4. 'firewalls' => [
    5. // 'main' is the name of the firewall (can be chosen freely)
    6. 'main' => [
    7. // 'pattern' is a regular expression matched against the incoming
    8. // request URL. If there's a match, authentication is triggered
    9. 'pattern' => '^/admin',
    10. // the rest of options depend on the authentication mechanism
    11. // ...
    12. ],
    13. ],
    14. ]);

See also

Read this article to learn about how to restrict firewalls by host and HTTP methods.

In addition to some common config options, the most important firewall options depend on the authentication mechanism, which can be any of these:

  1. # config/packages/security.yaml
  2. security:
  3. # ...
  4. firewalls:
  5. main:
  6. # ...
  7. x509:
  8. # ...
  9. remote_user:
  10. # ...
  11. simple_preauth:
  12. # ...
  13. guard:
  14. # ...
  15. form_login:
  16. # ...
  17. form_login_ldap:
  18. # ...
  19. json_login:
  20. # ...
  21. simple_form:
  22. # ...
  23. http_basic:
  24. # ...
  25. http_basic_ldap:
  26. # ...
  27. http_digest:
  28. # ...

form_login Authentication

When using the form_login authentication listener beneath a firewall, there are several common options for configuring the “form login” experience. For even more details, see Using the form_login Authentication Provider.

login_path

type: string default: /login

This is the route or path that the user will be redirected to (unless use_forward is set to true) when they try to access a protected resource but isn’t fully authenticated.

This path must be accessible by a normal, un-authenticated user, else you may create a redirect loop.

check_path

type: string default: /login_check

This is the route or path that your login form must submit to. The firewall will intercept any requests (POST requests only, by default) to this URL and process the submitted login credentials.

Be sure that this URL is covered by your main firewall (i.e. don’t create a separate firewall just for check_path URL).

use_forward

type: boolean default: false

If you’d like the user to be forwarded to the login form instead of being redirected, set this option to true.

username_parameter

type: string default: _username

This is the field name that you should give to the username field of your login form. When you submit the form to check_path, the security system will look for a POST parameter with this name.

password_parameter

type: string default: _password

This is the field name that you should give to the password field of your login form. When you submit the form to check_path, the security system will look for a POST parameter with this name.

post_only

type: boolean default: true

By default, you must submit your login form to the check_path URL as a POST request. By setting this option to false, you can send a GET request to the check_path URL.

Options Related to Redirecting after Login

always_use_default_target_path

type: boolean default: false

If true, users are always redirected to the default target path regardless of the previous URL that was stored in the session.

default_target_path

type: string default: /

The page users are redirected to when there is no previous page stored in the session (for example, when the users browse the login page directly).

target_path_parameter

type: string default: _target_path

When using a login form, if you include an HTML element to set the target path, this option lets you change the name of the HTML element itself.

failure_path_parameter

type: string default: _failure_path

When using a login form, if you include an HTML element to set the failure path, this option lets you change the name of the HTML element itself.

use_referer

type: boolean default: false

If true, the user is redirected to the value stored in the HTTP_REFERER header when no previous URL was stored in the session. If the referrer URL is the same as the one generated with the login_path route, the user is redirected to the default_target_path to avoid a redirection loop.

Note

For historical reasons, and to match the misspelling of the HTTP standard, the option is called use_referer instead of use_referrer.

Options Related to Logout Configuration

invalidate_session

type: boolean default: true

By default, when users log out from any firewall, their sessions are invalidated. This means that logging out from one firewall automatically logs them out from all the other firewalls.

The invalidate_session option allows to redefine this behavior. Set this option to false in every firewall and the user will only be logged out from the current firewall and not the other ones.

logout_on_user_change

type: boolean default: true

Deprecated since version 4.1: The logout_on_user_change option was deprecated in Symfony 4.1.

If false this option makes Symfony to not trigger a logout when the user has changed. Doing that is deprecated, so this option should be set to true or unset to avoid getting deprecation messages.

The user is considered to have changed when the user class implements Symfony\Component\Security\Core\User\EquatableInterface and the isEqualTo() method returns false. Also, when any of the properties required by the Symfony\Component\Security\Core\User\UserInterface (like the username, password or salt) changes.

path

type: string default: /logout

The path which triggers logout. If you change it from the default value /logout, you need to set up a route with a matching path.

target

type: string default: /

The relative path (if the value starts with /), or absolute URL (if it starts with http:// or https://) or the route name (otherwise) to redirect after logout.

success_handler

type: string default: 'security.logout.success_handler'

The service ID used for handling a successful logout. The service must implement Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface.

If it is set, the logout target option will be ignored.

csrf_parameter

type: string default: '_csrf_token'

The name of the parameter that stores the CSRF token value.

csrf_token_generator

type: string default: null

The id of the service used to generate the CSRF tokens. Symfony provides a default service whose ID is security.csrf.token_manager.

csrf_token_id

type: string default: 'logout'

An arbitrary string used to identify the token (and check its validity afterwards).

LDAP Authentication

There are several options for connecting against an LDAP server, using the form_login_ldap, http_basic_ldap and json_login_ldap authentication providers or the ldap user provider.

For even more details, see Authenticating against an LDAP server.

Authentication

You can authenticate to an LDAP server using the LDAP variants of the form_login, http_basic and json_login authentication providers. Use form_login_ldap, http_basic_ldap and json_login_ldap, which will attempt to bind against an LDAP server instead of using password comparison.

Both authentication providers have the same arguments as their normal counterparts, with the addition of two configuration keys:

service

type: string default: ldap

This is the name of your configured LDAP client.

dn_string

type: string default: {username}

This is the string which will be used as the bind DN. The {username} placeholder will be replaced with the user-provided value (their login). Depending on your LDAP server’s configuration, you may need to override this value.

query_string

type: string default: null

This is the string which will be used to query for the DN. The {username} placeholder will be replaced with the user-provided value (their login). Depending on your LDAP server’s configuration, you will need to override this value. This setting is only necessary if the user’s DN cannot be derived statically using the dn_string config option.

User provider

Users will still be fetched from the configured user provider. If you wish to fetch your users from an LDAP server, you will need to use the LDAP User Provider and any of these authentication providers: form_login_ldap or http_basic_ldap or json_login_ldap.

Firewall Context

Most applications will only need one firewall. But if your application does use multiple firewalls, you’ll notice that if you’re authenticated in one firewall, you’re not automatically authenticated in another. In other words, the systems don’t share a common “context”: each firewall acts like a separate security system.

However, each firewall has an optional context key (which defaults to the name of the firewall), which is used when storing and retrieving security data to and from the session. If this key were set to the same value across multiple firewalls, the “context” could actually be shared:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. firewalls:
    5. somename:
    6. # ...
    7. context: my_context
    8. othername:
    9. # ...
    10. context: my_context
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <firewall name="somename" context="my_context">
    10. <!-- ... -->
    11. </firewall>
    12. <firewall name="othername" context="my_context">
    13. <!-- ... -->
    14. </firewall>
    15. </config>
    16. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. 'firewalls' => [
    4. 'somename' => [
    5. // ...
    6. 'context' => 'my_context',
    7. ],
    8. 'othername' => [
    9. // ...
    10. 'context' => 'my_context',
    11. ],
    12. ],
    13. ]);

Note

The firewall context key is stored in session, so every firewall using it must set its stateless option to false. Otherwise, the context is ignored and you won’t be able to authenticate on multiple firewalls at the same time.

User Checkers

During the authentication of a user, additional checks might be required to verify if the identified user is allowed to log in. Each firewall can include a user_checker option to define the service used to perform those checks.

Learn more about user checkers in How to Create and Enable Custom User Checkers.

providers

This options defines how the application users are loaded (from a database, an LDAP server, a configuration file, etc.) Read the following articles to learn more about each of those providers:

role_hierarchy

Instead of associating many roles to users, this option allows you to define role inheritance rules by creating a role hierarchy, as explained in Hierarchical Roles.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.