Search code examples
symfonysymfony4symfony-security

Symfony4 different security configurations for different environments


I've seen instructions all over for doing this in symfony 3.4 but I can't figure out how to do this in Symfony 4. I have a custom environment and when a developer sets APP_ENV to that environment I want a different security.yaml to be used. Say for example I created a configuration environment 'local', when I have config/packages/local/security.yaml and APP_ENV=local, my app still defaults to config/packages/security.yaml. I want config/packages/security.yaml to be completely ignored in favor of config/packages/local/security.yaml.

Here is my prod/security.yaml:

security:
    providers:
        shibboleth:
            id: App\Security\User\ShibbolethUserProvider
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            stateless: true
            anonymous: ~
            guard:
                authenticators:
                    - app.shibboleth_authenticator

            logout:
                path: /logout
                success_handler: app.shibboleth_authenticator

    access_control:
        - { path: ^/result, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: ROLE_USER }

And here is my local/security.yaml:

security:
    providers:
        in_memory: { memory: ~ }
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~

Solution

  • In Symfony4 you split your configuration in environment folders. What you want to do is probably the following:

    .
    └── config
        └── packages
            ├── dev
            ├── local
            │   └── security.yaml
            ├── prod
            │   └── security.yaml
            └── tests
    

    It works this way thanks to this line inside your Kernel.php https://github.com/symfony/recipes/blob/34fc4212d838ac6c49a2b9892e2aa1d926149192/symfony/framework-bundle/3.3/src/Kernel.php#L48

    $loader->load($confDir.'/{packages}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, 'glob');