How to Use multiple User Providers

Version: 4.0
Edit this page

Warning: You are browsing the documentation for Symfony 4.0, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

How to Use multiple User Providers

Note

It's always better to use a specific user provider for each authentication mechanism. Chaining user providers should be avoided in most applications and used only to solve edge cases.

Each authentication mechanism (e.g. HTTP Authentication, form login, etc.) uses exactly one user provider. But what if you want to specify a few users via configuration and the rest of your users in the database? This is possible by creating a new provider that chains the two together:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
# config/packages/security.yaml
security:
    providers:
        chain_provider:
            chain:
                providers: [in_memory, user_db]
        in_memory:
            memory:
                users:
                    foo: { password: test }
        user_db:
            entity: { class: App\Entity\User, property: username }

Now, all firewalls that define chain_provider as their user provider will, in turn, try to load the user from both the in_memory and user_db providers.

You can also configure the firewall or individual authentication mechanisms to use a specific provider:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
# config/packages/security.yaml
security:
    firewalls:
        secured_area:
            # ...
            pattern: ^/
            provider: user_db
            http_basic:
                realm: 'Secured Demo Area'
                provider: in_memory
            form_login: ~

In this example, if a user tries to log in via HTTP authentication, the authentication system will use the in_memory user provider. But if the user tries to log in via the form login, the user_db provider will be used (since it's the default for the firewall as a whole).

If you need to check that the user being returned by your provider is a allowed to authenticate, check the returned user object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\Security\Core\User;
// ...

public function loadUserByUsername($username)
{
    // ...

    // you can, for example, test that the returned user is an object of a
    // particular class or check for certain attributes of your user objects
    if ($user instance User) {
        // the user was loaded from the main security config file. Do something.
        // ...
    }

    return $user;
}

For more information about user provider and firewall configuration, see the Security Configuration Reference (SecurityBundle).

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